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": 3, "code_window": [ " </FocusScope>\n", " </ClickOutsideWrapper>\n", " </div>\n", " )}\n", " </ButtonGroup>\n", " );\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " </div>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 85 }
import { adjustOperatorIfNeeded, getCondition, getOperator } from './tagUtils'; describe('InfluxDB InfluxQL Editor tag utils', () => { describe('getOperator', () => { it('should return an existing operator', () => { expect( getOperator({ key: 'key', value: 'value', operator: '!=', }) ).toBe('!='); }); it('should return = when missing operator', () => { expect( getOperator({ key: 'key', value: 'value', }) ).toBe('='); }); }); describe('getCondition', () => { it('should return an existing condition when not first', () => { expect( getCondition( { key: 'key', value: 'value', operator: '=', condition: 'OR', }, false ) ).toBe('OR'); }); it('should return AND when missing condition when not first', () => { expect( getCondition( { key: 'key', value: 'value', operator: '=', }, false ) ).toBe('AND'); }); it('should return undefined for an existing condition when first', () => { expect( getCondition( { key: 'key', value: 'value', operator: '=', condition: 'OR', }, true ) ).toBeUndefined(); }); it('should return undefined when missing condition when first', () => { expect( getCondition( { key: 'key', value: 'value', operator: '=', }, true ) ).toBeUndefined(); }); }); describe('adjustOperatorIfNeeded', () => { it('should keep operator when both operator and value are regex', () => { expect(adjustOperatorIfNeeded('=~', '/test/')).toBe('=~'); expect(adjustOperatorIfNeeded('!~', '/test/')).toBe('!~'); }); it('should keep operator when both operator and value are not regex', () => { expect(adjustOperatorIfNeeded('=', 'test')).toBe('='); expect(adjustOperatorIfNeeded('!=', 'test')).toBe('!='); }); it('should change operator to =~ when value is regex and operator is not regex', () => { expect(adjustOperatorIfNeeded('<>', '/test/')).toBe('=~'); }); it('should change operator to = when value is not regex and operator is regex', () => { expect(adjustOperatorIfNeeded('!~', 'test')).toBe('='); }); }); });
public/app/plugins/datasource/influxdb/components/editor/query/influxql/utils/tagUtils.test.ts
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.00017814199964050204, 0.00017328860121779144, 0.0001703538146102801, 0.00017280381871387362, 0.0000023240866084961453 ]
{ "id": 3, "code_window": [ " </FocusScope>\n", " </ClickOutsideWrapper>\n", " </div>\n", " )}\n", " </ButtonGroup>\n", " );\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " </div>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 85 }
package acimpl import ( "context" "fmt" "testing" "time" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol/actest" "github.com/grafana/grafana/pkg/services/accesscontrol/database" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/setting" ) // setupBenchEnv will create userCount users, userCount managed roles with resourceCount managed permission each // Example: setupBenchEnv(b, 2, 3): // - will create 2 users and assign them 2 managed roles // - each managed role will have 3 permissions {"resources:action2", "resources:id:x"} where x belongs to [1, 3] func setupBenchEnv(b *testing.B, usersCount, resourceCount int) (accesscontrol.Service, *user.SignedInUser) { now := time.Now() sqlStore := db.InitTestDB(b) store := database.ProvideService(sqlStore) acService := &Service{ cfg: setting.NewCfg(), log: log.New("accesscontrol-test"), registrations: accesscontrol.RegistrationList{}, store: store, roles: accesscontrol.BuildBasicRoleDefinitions(), } // Prepare default permissions action1 := "resources:action1" err := acService.DeclareFixedRoles(accesscontrol.RoleRegistration{ Role: accesscontrol.RoleDTO{Name: "fixed:test:role", Permissions: []accesscontrol.Permission{{Action: action1}}}, Grants: []string{string(org.RoleViewer)}, }) require.NoError(b, err) err = acService.RegisterFixedRoles(context.Background()) require.NoError(b, err) // Populate users, roles and assignments if errInsert := actest.ConcurrentBatch(actest.Concurrency, usersCount, actest.BatchSize, func(start, end int) error { n := end - start users := make([]user.User, 0, n) orgUsers := make([]org.OrgUser, 0, n) roles := make([]accesscontrol.Role, 0, n) userRoles := make([]accesscontrol.UserRole, 0, n) for u := start + 1; u < end+1; u++ { users = append(users, user.User{ ID: int64(u), Name: fmt.Sprintf("user%v", u), Login: fmt.Sprintf("user%v", u), Email: fmt.Sprintf("user%[email protected]", u), Created: now, Updated: now, }) orgUsers = append(orgUsers, org.OrgUser{ ID: int64(u), UserID: int64(u), OrgID: 1, Role: org.RoleViewer, Created: now, Updated: now, }) roles = append(roles, accesscontrol.Role{ ID: int64(u), UID: fmt.Sprintf("managed_users_%v_permissions", u), Name: fmt.Sprintf("managed:users:%v:permissions", u), OrgID: 1, Version: 1, Created: now, Updated: now, }) userRoles = append(userRoles, accesscontrol.UserRole{ ID: int64(u), OrgID: 1, RoleID: int64(u), UserID: int64(u), Created: now, }) } err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error { if _, err := sess.Insert(users); err != nil { return err } if _, err := sess.Insert(orgUsers); err != nil { return err } if _, err := sess.Insert(roles); err != nil { return err } _, err := sess.Insert(userRoles) return err }) return err }); errInsert != nil { require.NoError(b, errInsert, "could not insert users and roles") return nil, nil } // Populate permissions action2 := "resources:action2" if errInsert := actest.ConcurrentBatch(actest.Concurrency, resourceCount*usersCount, actest.BatchSize, func(start, end int) error { permissions := make([]accesscontrol.Permission, 0, end-start) for i := start; i < end; i++ { permissions = append(permissions, accesscontrol.Permission{ RoleID: int64(i/resourceCount + 1), Action: action2, Scope: fmt.Sprintf("resources:id:%v", i%resourceCount+1), Created: now, Updated: now, }) } return sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error { _, err := sess.Insert(permissions) return err }) }); errInsert != nil { require.NoError(b, errInsert, "could not insert permissions") return nil, nil } // Allow signed in user to view all users permissions in the worst way userPermissions := map[string][]string{} for u := 1; u < usersCount+1; u++ { userPermissions[accesscontrol.ActionUsersPermissionsRead] = append(userPermissions[accesscontrol.ActionUsersPermissionsRead], fmt.Sprintf("users:id:%v", u)) } return acService, &user.SignedInUser{OrgID: 1, Permissions: map[int64]map[string][]string{1: userPermissions}} } func benchSearchUsersPermissions(b *testing.B, usersCount, resourceCount int) { acService, siu := setupBenchEnv(b, usersCount, resourceCount) b.ResetTimer() for n := 0; n < b.N; n++ { usersPermissions, err := acService.SearchUsersPermissions(context.Background(), siu, accesscontrol.SearchOptions{ActionPrefix: "resources:"}) require.NoError(b, err) require.Len(b, usersPermissions, usersCount) for _, permissions := range usersPermissions { // action1 on all resource + action2 require.Len(b, permissions, resourceCount+1) } } } // Lots of resources func BenchmarkSearchUsersPermissions_10_1K(b *testing.B) { benchSearchUsersPermissions(b, 10, 1000) } // ~0.047s/op func BenchmarkSearchUsersPermissions_10_10K(b *testing.B) { benchSearchUsersPermissions(b, 10, 10000) } // ~0.5s/op func BenchmarkSearchUsersPermissions_10_100K(b *testing.B) { if testing.Short() { b.Skip("Skipping benchmark in short mode") } benchSearchUsersPermissions(b, 10, 100000) } // ~4.6s/op func BenchmarkSearchUsersPermissions_10_1M(b *testing.B) { if testing.Short() { b.Skip("Skipping benchmark in short mode") } benchSearchUsersPermissions(b, 10, 1000000) } // ~55.36s/op // Lots of users (most probable case) func BenchmarkSearchUsersPermissions_1K_10(b *testing.B) { benchSearchUsersPermissions(b, 1000, 10) } // ~0.056s/op func BenchmarkSearchUsersPermissions_10K_10(b *testing.B) { benchSearchUsersPermissions(b, 10000, 10) } // ~0.58s/op func BenchmarkSearchUsersPermissions_100K_10(b *testing.B) { if testing.Short() { b.Skip("Skipping benchmark in short mode") } benchSearchUsersPermissions(b, 100000, 10) } // ~6.21s/op func BenchmarkSearchUsersPermissions_1M_10(b *testing.B) { if testing.Short() { b.Skip("Skipping benchmark in short mode") } benchSearchUsersPermissions(b, 1000000, 10) } // ~57s/op // Lots of both func BenchmarkSearchUsersPermissions_10K_100(b *testing.B) { if testing.Short() { b.Skip("Skipping benchmark in short mode") } benchSearchUsersPermissions(b, 10000, 100) } // ~1.45s/op func BenchmarkSearchUsersPermissions_10K_1K(b *testing.B) { if testing.Short() { b.Skip("Skipping benchmark in short mode") } benchSearchUsersPermissions(b, 10000, 1000) } // ~50s/op // Benchmarking search when we specify Action and Scope func benchSearchUsersWithPerm(b *testing.B, usersCount, resourceCount int) { if testing.Short() { b.Skip("Skipping benchmark in short mode") } acService, siu := setupBenchEnv(b, usersCount, resourceCount) b.ResetTimer() for n := 0; n < b.N; n++ { usersPermissions, err := acService.SearchUsersPermissions(context.Background(), siu, accesscontrol.SearchOptions{Action: "resources:action2", Scope: "resources:id:1"}) require.NoError(b, err) require.Len(b, usersPermissions, usersCount) for _, permissions := range usersPermissions { require.Len(b, permissions, 1) } } } func BenchmarkSearchUsersWithPerm_1K_10(b *testing.B) { benchSearchUsersWithPerm(b, 1000, 10) } // ~0.045s/op func BenchmarkSearchUsersWithPerm_1K_100(b *testing.B) { benchSearchUsersWithPerm(b, 1000, 100) } // ~0.038s/op func BenchmarkSearchUsersWithPerm_1K_1K(b *testing.B) { benchSearchUsersWithPerm(b, 1000, 1000) } // ~0.033s/op func BenchmarkSearchUsersWithPerm_1K_10K(b *testing.B) { benchSearchUsersWithPerm(b, 1000, 10000) } // ~0.033s/op func BenchmarkSearchUsersWithPerm_1K_100K(b *testing.B) { benchSearchUsersWithPerm(b, 1000, 100000) } // ~0.056s/op func BenchmarkSearchUsersWithPerm_10K_10(b *testing.B) { benchSearchUsersWithPerm(b, 10000, 10) } // ~0.11s/op func BenchmarkSearchUsersWithPerm_10K_100(b *testing.B) { benchSearchUsersWithPerm(b, 10000, 100) } // ~0.12s/op func BenchmarkSearchUsersWithPerm_10K_1K(b *testing.B) { benchSearchUsersWithPerm(b, 10000, 1000) } // ~0.12s/op func BenchmarkSearchUsersWithPerm_10K_10K(b *testing.B) { benchSearchUsersWithPerm(b, 10000, 10000) } // ~0.17s/op func BenchmarkSearchUsersWithPerm_20K_10(b *testing.B) { benchSearchUsersWithPerm(b, 20000, 10) } // ~0.22s/op func BenchmarkSearchUsersWithPerm_20K_100(b *testing.B) { benchSearchUsersWithPerm(b, 20000, 100) } // ~0.22s/op func BenchmarkSearchUsersWithPerm_20K_1K(b *testing.B) { benchSearchUsersWithPerm(b, 20000, 1000) } // ~0.25s/op func BenchmarkSearchUsersWithPerm_20K_10K(b *testing.B) { benchSearchUsersWithPerm(b, 20000, 10000) } // ~s/op func BenchmarkSearchUsersWithPerm_100K_10(b *testing.B) { benchSearchUsersWithPerm(b, 100000, 10) } // ~0.88s/op func BenchmarkSearchUsersWithPerm_100K_100(b *testing.B) { benchSearchUsersWithPerm(b, 100000, 100) } // ~0.72s/op
pkg/services/accesscontrol/acimpl/service_bench_test.go
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.000257519306614995, 0.0001749245129758492, 0.0001655480737099424, 0.00017256761202588677, 0.000017464530174038373 ]
{ "id": 0, "code_window": [ "\n", " var errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2);\n", " errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon, typeToString(type), typeName1, typeName2);\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1000 }
/// <reference path="core.ts"/> /// <reference path="scanner.ts"/> module ts { export interface TextRange { pos: number; end: number; } // token > SyntaxKind.Identifer => token is a keyword export enum SyntaxKind { Unknown, EndOfFileToken, // Literals NumericLiteral, StringLiteral, RegularExpressionLiteral, // Punctuation OpenBraceToken, CloseBraceToken, OpenParenToken, CloseParenToken, OpenBracketToken, CloseBracketToken, DotToken, DotDotDotToken, SemicolonToken, CommaToken, LessThanToken, GreaterThanToken, LessThanEqualsToken, GreaterThanEqualsToken, EqualsEqualsToken, ExclamationEqualsToken, EqualsEqualsEqualsToken, ExclamationEqualsEqualsToken, EqualsGreaterThanToken, PlusToken, MinusToken, AsteriskToken, SlashToken, PercentToken, PlusPlusToken, MinusMinusToken, LessThanLessThanToken, GreaterThanGreaterThanToken, GreaterThanGreaterThanGreaterThanToken, AmpersandToken, BarToken, CaretToken, ExclamationToken, TildeToken, AmpersandAmpersandToken, BarBarToken, QuestionToken, ColonToken, // Assignments EqualsToken, PlusEqualsToken, MinusEqualsToken, AsteriskEqualsToken, SlashEqualsToken, PercentEqualsToken, LessThanLessThanEqualsToken, GreaterThanGreaterThanEqualsToken, GreaterThanGreaterThanGreaterThanEqualsToken, AmpersandEqualsToken, BarEqualsToken, CaretEqualsToken, // Identifiers Identifier, // Reserved words BreakKeyword, CaseKeyword, CatchKeyword, ClassKeyword, ConstKeyword, ContinueKeyword, DebuggerKeyword, DefaultKeyword, DeleteKeyword, DoKeyword, ElseKeyword, EnumKeyword, ExportKeyword, ExtendsKeyword, FalseKeyword, FinallyKeyword, ForKeyword, FunctionKeyword, IfKeyword, ImportKeyword, InKeyword, InstanceOfKeyword, NewKeyword, NullKeyword, ReturnKeyword, SuperKeyword, SwitchKeyword, ThisKeyword, ThrowKeyword, TrueKeyword, TryKeyword, TypeOfKeyword, VarKeyword, VoidKeyword, WhileKeyword, WithKeyword, // Strict mode reserved words ImplementsKeyword, InterfaceKeyword, LetKeyword, PackageKeyword, PrivateKeyword, ProtectedKeyword, PublicKeyword, StaticKeyword, YieldKeyword, // TypeScript keywords AnyKeyword, BooleanKeyword, ConstructorKeyword, DeclareKeyword, GetKeyword, ModuleKeyword, RequireKeyword, NumberKeyword, SetKeyword, StringKeyword, // Parse tree nodes Missing, // Names QualifiedName, // Signature elements TypeParameter, Parameter, // TypeMember Property, Method, Constructor, GetAccessor, SetAccessor, CallSignature, ConstructSignature, IndexSignature, // Type TypeReference, TypeQuery, TypeLiteral, ArrayType, // Expression ArrayLiteral, ObjectLiteral, PropertyAssignment, PropertyAccess, IndexedAccess, CallExpression, NewExpression, TypeAssertion, ParenExpression, FunctionExpression, ArrowFunction, PrefixOperator, PostfixOperator, BinaryExpression, ConditionalExpression, OmittedExpression, // Element Block, VariableStatement, EmptyStatement, ExpressionStatement, IfStatement, DoStatement, WhileStatement, ForStatement, ForInStatement, ContinueStatement, BreakStatement, ReturnStatement, WithStatement, SwitchStatement, CaseClause, DefaultClause, LabelledStatement, ThrowStatement, TryStatement, TryBlock, CatchBlock, FinallyBlock, DebuggerStatement, VariableDeclaration, FunctionDeclaration, FunctionBlock, ClassDeclaration, InterfaceDeclaration, EnumDeclaration, ModuleDeclaration, ModuleBlock, ImportDeclaration, ExportAssignment, // Enum EnumMember, // Top-level nodes SourceFile, Program, // Synthesized list SyntaxList, // Enum value count Count, // Markers FirstAssignment = EqualsToken, LastAssignment = CaretEqualsToken, FirstReservedWord = BreakKeyword, LastReservedWord = WithKeyword, FirstKeyword = BreakKeyword, LastKeyword = StringKeyword, FirstFutureReservedWord = ImplementsKeyword, LastFutureReservedWord = YieldKeyword } export enum NodeFlags { Export = 0x00000001, // Declarations Ambient = 0x00000002, // Declarations QuestionMark = 0x00000004, // Parameter/Property/Method Rest = 0x00000008, // Parameter Public = 0x00000010, // Property/Method Private = 0x00000020, // Property/Method Static = 0x00000040, // Property/Method MultiLine = 0x00000080, // Multi-line array or object literal Synthetic = 0x00000100, // Synthetic node (for full fidelity) DeclarationFile = 0x00000200, // Node is a .d.ts file Modifier = Export | Ambient | Public | Private | Static } export interface Node extends TextRange { kind: SyntaxKind; flags: NodeFlags; id?: number; // Unique id (used to look up NodeLinks) parent?: Node; // Parent node (initialized by binding) symbol?: Symbol; // Symbol declared by node (initialized by binding) locals?: SymbolTable; // Locals associated with node (initialized by binding) nextContainer?: Node; // Next container in declaration order (initialized by binding) localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes) } export interface NodeArray<T> extends Array<T>, TextRange { } export interface Identifier extends Node { text: string; // Text of identifier (with escapes converted to characters) } export interface QualifiedName extends Node { // Must have same layout as PropertyAccess left: EntityName; right: Identifier; } export interface EntityName extends Node { // Identifier, QualifiedName, or Missing } export interface ParsedSignature { typeParameters?: NodeArray<TypeParameterDeclaration>; parameters: NodeArray<ParameterDeclaration>; type?: TypeNode; } export interface Declaration extends Node { name?: Identifier; } export interface TypeParameterDeclaration extends Declaration { constraint?: TypeNode; } export interface SignatureDeclaration extends Declaration, ParsedSignature { } export interface VariableDeclaration extends Declaration { type?: TypeNode; initializer?: Expression; } export interface PropertyDeclaration extends VariableDeclaration { } export interface ParameterDeclaration extends VariableDeclaration { } export interface FunctionDeclaration extends Declaration, ParsedSignature { body?: Node; // Block or Expression } export interface MethodDeclaration extends FunctionDeclaration { } export interface ConstructorDeclaration extends FunctionDeclaration { } export interface AccessorDeclaration extends FunctionDeclaration { } export interface TypeNode extends Node { } export interface TypeReferenceNode extends TypeNode { typeName: EntityName; typeArguments?: NodeArray<TypeNode>; } export interface TypeQueryNode extends TypeNode { exprName: EntityName; } export interface TypeLiteralNode extends TypeNode { members: NodeArray<Node>; } export interface ArrayTypeNode extends TypeNode { elementType: TypeNode; } export interface StringLiteralTypeNode extends TypeNode { text: string; } export interface Expression extends Node { } export interface UnaryExpression extends Expression { operator: SyntaxKind; operand: Expression; } export interface BinaryExpression extends Expression { left: Expression; operator: SyntaxKind; right: Expression; } export interface ConditionalExpression extends Expression { condition: Expression; whenTrue: Expression; whenFalse: Expression; } export interface FunctionExpression extends Expression, FunctionDeclaration { body: Node; // Required, whereas the member inherited from FunctionDeclaration is optional } // The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral // this means quotes have been removed and escapes have been converted to actual characters. For a NumericLiteral, the // stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1". export interface LiteralExpression extends Expression { text: string; } export interface ParenExpression extends Expression { expression: Expression; } export interface ArrayLiteral extends Expression { elements: NodeArray<Expression>; } export interface ObjectLiteral extends Expression { properties: NodeArray<Node>; } export interface PropertyAccess extends Expression { left: Expression; right: Identifier; } export interface IndexedAccess extends Expression { object: Expression; index: Expression; } export interface CallExpression extends Expression { func: Expression; typeArguments?: NodeArray<TypeNode>; arguments: NodeArray<Expression>; } export interface NewExpression extends CallExpression { } export interface TypeAssertion extends Expression { type: TypeNode; operand: Expression; } export interface Statement extends Node { } export interface Block extends Statement { statements: NodeArray<Statement>; } export interface VariableStatement extends Statement { declarations: NodeArray<VariableDeclaration>; } export interface ExpressionStatement extends Statement { expression: Expression; } export interface IfStatement extends Statement { expression: Expression; thenStatement: Statement; elseStatement?: Statement; } export interface IterationStatement extends Statement { statement: Statement; } export interface DoStatement extends IterationStatement { expression: Expression; } export interface WhileStatement extends IterationStatement { expression: Expression; } export interface ForStatement extends IterationStatement { declarations?: NodeArray<VariableDeclaration>; initializer?: Expression; condition?: Expression; iterator?: Expression; } export interface ForInStatement extends IterationStatement { declaration?: VariableDeclaration; variable?: Expression; expression: Expression; } export interface BreakOrContinueStatement extends Statement { label?: Identifier; } export interface ReturnStatement extends Statement { expression?: Expression; } export interface WithStatement extends Statement { expression: Expression; statement: Statement; } export interface SwitchStatement extends Statement { expression: Expression; clauses: NodeArray<CaseOrDefaultClause>; } export interface CaseOrDefaultClause extends Node { expression?: Expression; statements: NodeArray<Statement>; } export interface LabelledStatement extends Statement { label: Identifier; statement: Statement; } export interface ThrowStatement extends Statement { expression: Expression; } export interface TryStatement extends Statement { tryBlock: Block; catchBlock?: CatchBlock; finallyBlock?: Block; } export interface CatchBlock extends Block { variable: Identifier; } export interface ClassDeclaration extends Declaration { typeParameters?: NodeArray<TypeParameterDeclaration>; baseType?: TypeReferenceNode; implementedTypes?: NodeArray<TypeReferenceNode>; members: NodeArray<Node>; } export interface InterfaceDeclaration extends Declaration { typeParameters?: NodeArray<TypeParameterDeclaration>; baseTypes?: NodeArray<TypeReferenceNode>; members: NodeArray<Node>; } export interface EnumMember extends Declaration { initializer?: Expression; } export interface EnumDeclaration extends Declaration { members: NodeArray<EnumMember>; } export interface ModuleDeclaration extends Declaration { body: Node; // Block or ModuleDeclaration } export interface ImportDeclaration extends Declaration { entityName?: EntityName; externalModuleName?: LiteralExpression; } export interface ExportAssignment extends Statement { exportName: Identifier; } export interface FileReference extends TextRange { filename: string; } export interface SourceFile extends Block { filename: string; text: string; getLineAndCharacterFromPosition(position: number): { line: number; character: number }; amdDependencies: string[]; referencedFiles: FileReference[]; syntacticErrors: Diagnostic[]; semanticErrors: Diagnostic[]; hasNoDefaultLib: boolean; externalModuleIndicator: Node; // The first node that causes this file to be an external module nodeCount: number; identifierCount: number; symbolCount: number; } export interface Program { getSourceFile(filename: string): SourceFile; getSourceFiles(): SourceFile[]; getCompilerOptions(): CompilerOptions; getCompilerHost(): CompilerHost; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getTypeChecker(): TypeChecker; getCommonSourceDirectory(): string; } export interface SourceMapSpan { /** Line number in the js file*/ emittedLine: number; /** Column number in the js file */ emittedColumn: number; /** Line number in the ts file */ sourceLine: number; /** Column number in the ts file */ sourceColumn: number; /** Optional name (index into names array) associated with this span */ nameIndex?: number; /** ts file (index into sources array) associated with this span*/ sourceIndex: number; } export interface SourceMapData { /** Where the sourcemap file is written */ sourceMapFilePath: string; /** source map url written in the js file */ jsSourceMappingURL: string; /** Source map's file field - js file name*/ sourceMapFile: string; /** Source map's sourceRoot field - location where the sources will be present if not "" */ sourceMapSourceRoot: string; /** Source map's sources field - list of sources that can be indexed in this source map*/ sourceMapSources: string[]; /** input source file (which one can use on program to get the file) this is one to one mapping with the sourceMapSources list*/ inputSourceFileNames: string[]; /** Source map's names field - list of names that can be indexed in this source map*/ sourceMapNames?: string[]; /** Source map's mapping field - encoded source map spans*/ sourceMapMappings: string; /** Raw source map spans that were encoded into the sourceMapMappings*/ sourceMapDecodedMappings: SourceMapSpan[]; } export interface EmitResult { errors: Diagnostic[]; sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps } export interface TypeChecker { getProgram(): Program; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; getTypeCount(): number; checkProgram(): void; emitFiles(): EmitResult; getSymbolOfNode(node: Node): Symbol; getParentOfSymbol(symbol: Symbol): Symbol; getTypeOfSymbol(symbol: Symbol): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; getIndexTypeOfType(type: Type, kind: IndexKind): Type; getReturnTypeOfSignature(signature: Signature): Type; resolveEntityName(location: Node, name: EntityName, meaning: SymbolFlags): Symbol; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolOfIdentifier(identifier: Identifier): Symbol; } export interface TextWriter { write(s: string): void; writeLine(): void; increaseIndent(): void; decreaseIndent(): void; getText(): string; } export enum TypeFormatFlags { None = 0x00000000, /** writes Array<T> instead T[] */ WriteArrayAsGenericType = 0x00000001, // Declarations } export interface EmitResolver { getProgram(): Program; getLocalNameOfContainer(container: Declaration): string; getExpressionNamePrefix(node: Identifier): string; getPropertyAccessSubstitution(node: PropertyAccess): string; getExportAssignmentName(node: SourceFile): string; isReferencedImportDeclaration(node: ImportDeclaration): boolean; isTopLevelValueImportedViaEntityName(node: ImportDeclaration): boolean; getNodeCheckFlags(node: Node): NodeCheckFlags; getEnumMemberValue(node: EnumMember): number; shouldEmitDeclarations(): boolean; isDeclarationVisible(node: Declaration): boolean; isImplementationOfOverload(node: FunctionDeclaration): boolean; writeTypeAtLocation(location: Node, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter): void; writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter): void; } export enum SymbolFlags { Variable = 0x00000001, // Variable or parameter Property = 0x00000002, // Property or enum member EnumMember = 0x00000004, // Enum member Function = 0x00000008, // Function Class = 0x00000010, // Class Interface = 0x00000020, // Interface Enum = 0x00000040, // Enum ValueModule = 0x00000080, // Instantiated module NamespaceModule = 0x00000100, // Uninstantiated module TypeLiteral = 0x00000200, // Type Literal ObjectLiteral = 0x00000400, // Object Literal Method = 0x00000800, // Method Constructor = 0x00001000, // Constructor GetAccessor = 0x00002000, // Get accessor SetAccessor = 0x00004000, // Set accessor CallSignature = 0x00008000, // Call signature ConstructSignature = 0x00010000, // Construct signature IndexSignature = 0x00020000, // Index signature TypeParameter = 0x00040000, // Type parameter // Export markers (see comment in declareModuleMember in binder) ExportValue = 0x00080000, // Exported value marker ExportType = 0x00100000, // Exported type marker ExportNamespace = 0x00200000, // Exported namespace marker Import = 0x00400000, // Import Instantiated = 0x00800000, // Instantiated symbol Merged = 0x01000000, // Merged symbol (created during program binding) Transient = 0x02000000, // Transient symbol (created during type check) Prototype = 0x04000000, // Symbol for the prototype property (without source code representation) Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor, Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter, Namespace = ValueModule | NamespaceModule, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, Signature = CallSignature | ConstructSignature | IndexSignature, ParameterExcludes = Value, VariableExcludes = Value & ~Variable, PropertyExcludes = Value, EnumMemberExcludes = Value, FunctionExcludes = Value & ~(Function | ValueModule), ClassExcludes = (Value | Type) & ~ValueModule, InterfaceExcludes = Type & ~Interface, EnumExcludes = (Value | Type) & ~(Enum | ValueModule), ValueModuleExcludes = Value & ~(Function | Class | Enum | ValueModule), NamespaceModuleExcludes = 0, MethodExcludes = Value & ~Method, GetAccessorExcludes = Value & ~SetAccessor, SetAccessorExcludes = Value & ~GetAccessor, TypeParameterExcludes = Type & ~TypeParameter, // Imports collide with all other imports with the same name. ImportExcludes = Import, ModuleMember = Variable | Function | Class | Interface | Enum | Module | Import, ExportHasLocal = Function | Class | Enum | ValueModule, HasLocals = Function | Module | Method | Constructor | Accessor | Signature, HasExports = Class | Enum | Module, HasMembers = Class | Interface | TypeLiteral | ObjectLiteral, IsContainer = HasLocals | HasExports | HasMembers, PropertyOrAccessor = Property | Accessor, Export = ExportNamespace | ExportType | ExportValue, } export interface Symbol { flags: SymbolFlags; // Symbol flags name: string; // Name of symbol id?: number; // Unique id (used to look up SymbolLinks) mergeId?: number; // Merge id (used to look up merged symbol) declarations?: Declaration[]; // Declarations associated with this symbol parent?: Symbol; // Parent symbol members?: SymbolTable; // Class, interface or literal instance members exports?: SymbolTable; // Module exports exportSymbol?: Symbol; // Exported symbol associated with this symbol exportAssignSymbol?: Symbol; // Symbol exported from external module valueDeclaration?: Declaration // First value declaration of the symbol } export interface SymbolLinks { target?: Symbol; // Resolved (non-alias) target of an alias type?: Type; // Type of value symbol declaredType?: Type; // Type of class, interface, enum, or type parameter mapper?: TypeMapper; // Type mapper for instantiation alias referenced?: boolean; // True if alias symbol has been referenced as a value } export interface TransientSymbol extends Symbol, SymbolLinks { } export interface SymbolTable { [index: string]: Symbol; } export enum NodeCheckFlags { TypeChecked = 0x00000001, // Node has been type checked LexicalThis = 0x00000002, // Lexical 'this' reference CaptureThis = 0x00000004, // Lexical 'this' used in body EmitExtends = 0x00000008, // Emit __extends SuperInstance = 0x00000010, // Instance 'super' reference SuperStatic = 0x00000020, // Static 'super' reference } export interface NodeLinks { resolvedType?: Type; // Cached type of type node resolvedSignature?: Signature; // Cached signature of signature node resolvedSymbol?: Symbol; // Cached name resolution result flags?: NodeCheckFlags; // Set of flags specific to Node enumMemberValue?: number; // Constant value of enum member isIllegalTypeReferenceInConstraint?: boolean; // Is type reference in constraint refers to the type parameter from the same list isVisible?: boolean; // Is this node visible localModuleName?: string; // Local name for module instance } export enum TypeFlags { Any = 0x00000001, String = 0x00000002, Number = 0x00000004, Boolean = 0x00000008, Void = 0x00000010, Undefined = 0x00000020, Null = 0x00000040, Enum = 0x00000080, // Enum type StringLiteral = 0x00000100, // String literal type TypeParameter = 0x00000200, // Type parameter Class = 0x00000400, // Class Interface = 0x00000800, // Interface Reference = 0x00001000, // Generic type reference Anonymous = 0x00002000, // Anonymous FromSignature = 0x00004000, // Created for signature assignment check Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null, StringLike = String | StringLiteral, NumberLike = Number | Enum, ObjectType = Class | Interface | Reference | Anonymous } // Properties common to all types export interface Type { flags: TypeFlags; // Flags id: number; // Unique ID symbol?: Symbol; // Symbol associated with type (if any) } // Intrinsic types (TypeFlags.Intrinsic) export interface IntrinsicType extends Type { intrinsicName: string; // Name of intrinsic type } // String literal types (TypeFlags.StringLiteral) export interface StringLiteralType extends Type { text: string; // Text of string literal } // Object types (TypeFlags.ObjectType) export interface ObjectType extends Type { } export interface ApparentType extends Type { // This property is not used. It is just to make the type system think ApparentType // is a strict subtype of Type. _apparentTypeBrand: any; } // Class and interface types (TypeFlags.Class and TypeFlags.Interface) export interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) baseTypes: ObjectType[]; // Base types declaredProperties: Symbol[]; // Declared members declaredCallSignatures: Signature[]; // Declared call signatures declaredConstructSignatures: Signature[]; // Declared construct signatures declaredStringIndexType: Type; // Declared string index type declaredNumberIndexType: Type; // Declared numeric index type } // Type references (TypeFlags.Reference) export interface TypeReference extends ObjectType { target: GenericType; // Type reference target typeArguments: Type[]; // Type reference type arguments } // Generic class and interface types export interface GenericType extends InterfaceType, TypeReference { instantiations: Map<TypeReference>; // Generic instantiation cache openReferenceTargets: GenericType[]; // Open type reference targets openReferenceChecks: Map<boolean>; // Open type reference check cache } // Resolved object type export interface ResolvedObjectType extends ObjectType { members: SymbolTable; // Properties by name properties: Symbol[]; // Properties callSignatures: Signature[]; // Call signatures of type constructSignatures: Signature[]; // Construct signatures of type stringIndexType: Type; // String index type numberIndexType: Type; // Numeric index type } // Type parameters (TypeFlags.TypeParameter) export interface TypeParameter extends Type { constraint: Type; // Constraint target?: TypeParameter; // Instantiation target mapper?: TypeMapper; // Instantiation mapper } export enum SignatureKind { Call, Construct, } export interface Signature { declaration: SignatureDeclaration; // Originating declaration typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters resolvedReturnType: Type; // Resolved return type minArgumentCount: number; // Number of non-optional parameters hasRestParameter: boolean; // True if last parameter is rest parameter hasStringLiterals: boolean; // True if instantiated target?: Signature; // Instantiation target mapper?: TypeMapper; // Instantiation mapper erasedSignatureCache?: Signature; // Erased version of signature (deferred) isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison } export enum IndexKind { String, Number, } export interface TypeMapper { (t: Type): Type; } export interface InferenceContext { typeParameters: TypeParameter[]; inferences: Type[][]; inferredTypes: Type[]; } export interface DiagnosticMessage { key: string; category: DiagnosticCategory; code: number; } // A linked list of formatted diagnostic messages to be used as part of a multiline message. // It is built from the bottom up, leaving the head to be the "main" diagnostic. // While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, // the difference is that messages are all preformatted in DMC. export interface DiagnosticMessageChain { messageText: string; category: DiagnosticCategory; code: number; next?: DiagnosticMessageChain; } export interface Diagnostic { file: SourceFile; start: number; length: number; messageText: string; category: DiagnosticCategory; code: number; } export enum DiagnosticCategory { Warning, Error, Message, NoPrefix } export interface CompilerOptions { charset?: string; codepage?: number; declaration?: boolean; diagnostics?: boolean; help?: boolean; locale?: string; mapRoot?: string; module?: ModuleKind; noImplicitAny?: boolean; noLib?: boolean; noLibCheck?: boolean; noResolve?: boolean; out?: string; outDir?: string; removeComments?: boolean; sourceMap?: boolean; sourceRoot?: string; target?: ScriptTarget; version?: boolean; [option: string]: any; } export enum ModuleKind { None, CommonJS, AMD, } export enum ScriptTarget { ES3, ES5, } export interface ParsedCommandLine { options: CompilerOptions; filenames: string[]; errors: Diagnostic[]; } export interface CommandLineOption { name: string; type: any; error?: DiagnosticMessage; } export enum CharacterCodes { nullCharacter = 0, maxAsciiCharacter = 0x7F, lineFeed = 0x0A, // \n carriageReturn = 0x0D, // \r lineSeparator = 0x2028, paragraphSeparator = 0x2029, // REVIEW: do we need to support this? The scanner doesn't, but our IText does. This seems // like an odd disparity? (Or maybe it's completely fine for them to be different). nextLine = 0x0085, // Unicode 3.0 space characters space = 0x0020, // " " nonBreakingSpace = 0x00A0, // enQuad = 0x2000, emQuad = 0x2001, enSpace = 0x2002, emSpace = 0x2003, threePerEmSpace = 0x2004, fourPerEmSpace = 0x2005, sixPerEmSpace = 0x2006, figureSpace = 0x2007, punctuationSpace = 0x2008, thinSpace = 0x2009, hairSpace = 0x200A, zeroWidthSpace = 0x200B, narrowNoBreakSpace = 0x202F, ideographicSpace = 0x3000, mathematicalSpace = 0x205F, ogham = 0x1680, _ = 0x5F, $ = 0x24, _0 = 0x30, _1 = 0x31, _2 = 0x32, _3 = 0x33, _4 = 0x34, _5 = 0x35, _6 = 0x36, _7 = 0x37, _8 = 0x38, _9 = 0x39, a = 0x61, b = 0x62, c = 0x63, d = 0x64, e = 0x65, f = 0x66, g = 0x67, h = 0x68, i = 0x69, j = 0x6A, k = 0x6B, l = 0x6C, m = 0x6D, n = 0x6E, o = 0x6F, p = 0x70, q = 0x71, r = 0x72, s = 0x73, t = 0x74, u = 0x75, v = 0x76, w = 0x77, x = 0x78, y = 0x79, z = 0x7A, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4A, K = 0x4B, L = 0x4C, M = 0x4D, N = 0x4E, O = 0x4F, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5a, ampersand = 0x26, // & asterisk = 0x2A, // * at = 0x40, // @ backslash = 0x5C, // \ bar = 0x7C, // | caret = 0x5E, // ^ closeBrace = 0x7D, // } closeBracket = 0x5D, // ] closeParen = 0x29, // ) colon = 0x3A, // : comma = 0x2C, // , dot = 0x2E, // . doubleQuote = 0x22, // " equals = 0x3D, // = exclamation = 0x21, // ! greaterThan = 0x3E, // > lessThan = 0x3C, // < minus = 0x2D, // - openBrace = 0x7B, // { openBracket = 0x5B, // [ openParen = 0x28, // ( percent = 0x25, // % plus = 0x2B, // + question = 0x3F, // ? semicolon = 0x3B, // ; singleQuote = 0x27, // ' slash = 0x2F, // / tilde = 0x7E, // ~ backspace = 0x08, // \b formFeed = 0x0C, // \f byteOrderMark = 0xFEFF, tab = 0x09, // \t verticalTab = 0x0B, // \v } export interface CancellationToken { isCancellationRequested(): boolean; } export interface CompilerHost { getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; getDefaultLibFilename(): string; getCancellationToken? (): CancellationToken; writeFile(filename: string, data: string, onError?: (message: string) => void): void; getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; } }
src/compiler/types.ts
1
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.0032722651958465576, 0.00023841374786570668, 0.00015976834401953965, 0.00017080680117942393, 0.00037184375105425715 ]
{ "id": 0, "code_window": [ "\n", " var errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2);\n", " errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon, typeToString(type), typeName1, typeName2);\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1000 }
"use strict"; ++eval;
tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode7.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.0001701591827441007, 0.0001701591827441007, 0.0001701591827441007, 0.0001701591827441007, 0 ]
{ "id": 0, "code_window": [ "\n", " var errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2);\n", " errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon, typeToString(type), typeName1, typeName2);\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1000 }
/// <reference path="fourslash.ts"/> ////var x = [1, 2, 3]; ////var y/*y*/ = x./*1*/pop/*2*/(5); //// verify.errorExistsBetweenMarkers("1", "2"); verify.numberOfErrorsInCurrentFile(2); // Expected errors are: // - Supplied parameters do not match any signature of call target. // - Could not select overload for 'call' expression. goTo.marker("y"); verify.quickInfoIs("any"); goTo.eof(); edit.insert("interface Array<T> { pop(def: T): T; }"); verify.not.errorExistsBetweenMarkers("1", "2"); goTo.marker("y"); verify.quickInfoIs("number"); verify.numberOfErrorsInCurrentFile(0);
tests/cases/fourslash_old/extendArrayInterfaceMember.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017440575174987316, 0.00017284200293943286, 0.0001704781170701608, 0.00017364212544634938, 0.0000017003394532366656 ]
{ "id": 0, "code_window": [ "\n", " var errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2);\n", " errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon, typeToString(type), typeName1, typeName2);\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1000 }
//// [collisionRestParameterInType.ts] var v1: (_i: number, ...restParameters) => void; // no error - no code gen var v2: { (_i: number, ...restParameters); // no error - no code gen new (_i: number, ...restParameters); // no error - no code gen foo(_i: number, ...restParameters); // no error - no code gen prop: (_i: number, ...restParameters) => void; // no error - no code gen } //// [collisionRestParameterInType.js] var v1; var v2;
tests/baselines/reference/collisionRestParameterInType.js
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00016827735817059875, 0.000166176789207384, 0.00016407622024416924, 0.000166176789207384, 0.000002100568963214755 ]
{ "id": 1, "code_window": [ " var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, chainedMessage, terminalMessage);\n", " if (overflow) {\n", " error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));\n", " }\n", " else if (errorInfo) {\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));\n", " }\n", " return result;\n", "\n", " function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1047 }
/// <reference path="types.ts"/> module ts { export interface Map<T> { [index: string]: T; } export interface StringSet extends Map<any> { } export function forEach<T, U>(array: T[], callback: (element: T) => U): U { var result: U; if (array) { for (var i = 0, len = array.length; i < len; i++) { if (result = callback(array[i])) break; } } return result; } export function contains<T>(array: T[], value: T): boolean { if (array) { var len = array.length; for (var i = 0; i < len; i++) { if (array[i] === value) { return true; } } } return false; } export function indexOf<T>(array: T[], value: T): number { if (array) { var len = array.length; for (var i = 0; i < len; i++) { if (array[i] === value) { return i; } } } return -1; } export function filter<T>(array: T[], f: (x: T) => boolean): T[] { var result: T[]; if (array) { result = []; for (var i = 0, len = array.length; i < len; i++) { var item = array[i]; if (f(item)) { result.push(item); } } } return result; } export function map<T, U>(array: T[], f: (x: T) => U): U[] { var result: U[]; if (array) { result = []; var len = array.length; for (var i = 0; i < len; i++) { result.push(f(array[i])); } } return result; } export function concatenate<T>(array1: T[], array2: T[]): T[] { if (!array2.length) return array1; if (!array1.length) return array2; return array1.concat(array2); } export function sum(array: any[], prop: string): number { var result = 0; for (var i = 0; i < array.length; i++) { result += array[i][prop]; } return result; } export function binarySearch(array: number[], value: number): number { var low = 0; var high = array.length - 1; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; if (midValue === value) { return middle; } else if (midValue > value) { high = middle - 1; } else { low = middle + 1; } } return ~low; } var hasOwnProperty = Object.prototype.hasOwnProperty; export function hasProperty<T>(map: Map<T>, key: string): boolean { return hasOwnProperty.call(map, key); } export function getProperty<T>(map: Map<T>, key: string): T { return hasOwnProperty.call(map, key) ? map[key] : undefined; } export function isEmpty<T>(map: Map<T>) { for (var id in map) return false; return true; } export function clone<T>(object: T): T { var result: any = {}; for (var id in object) { result[id] = (<any>object)[id]; } return <T>result; } export function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U { var result: U; for (var id in map) { if (result = callback(map[id])) break; } return result; } export function mapToArray<T>(map: Map<T>): T[] { var result: T[] = []; for (var id in map) result.push(map[id]); return result; } function formatStringFromArgs(text: string, args: { [index: number]: any; }, baseIndex?: number): string { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, (match, index?) => args[+index + baseIndex]); } export var localizedDiagnosticMessages: Map<string> = undefined; function getLocaleSpecificMessage(message: string) { if (ts.localizedDiagnosticMessages) { message = localizedDiagnosticMessages[message]; } /* Check to see that we got an actual value back. */ Debug.assert(message, "Diagnostic message does not exist in locale map."); return message; } export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): Diagnostic { var text = getLocaleSpecificMessage(message.key); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); } return { file: file, start: start, length: length, messageText: text, category: message.category, code: message.code }; } export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { var text = getLocaleSpecificMessage(message.key); if (arguments.length > 1) { text = formatStringFromArgs(text, arguments, 1); } return { file: undefined, start: undefined, length: undefined, messageText: text, category: message.category, code: message.code }; } export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain; export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage): DiagnosticMessageChain { var text = getLocaleSpecificMessage(message.key); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); } return { messageText: text, category: message.category, code: message.code, next: details } } export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain): Diagnostic { var code = diagnosticChain.code; var category = diagnosticChain.category; var messageText = ""; var indent = 0; while (diagnosticChain) { if (indent) { messageText += sys.newLine; for (var i = 0; i < indent; i++) { messageText += " "; } } messageText += diagnosticChain.messageText; indent++; diagnosticChain = diagnosticChain.next; } return { file: file, start: start, length: length, code: code, category: category, messageText: messageText }; } function compareValues(a: any, b: any): number { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; return a < b ? -1 : 1; } function getDiagnosticFilename(diagnostic: Diagnostic): string { return diagnostic.file ? diagnostic.file.filename : undefined; } export function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): number { return compareValues(getDiagnosticFilename(d1), getDiagnosticFilename(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || compareValues(d1.messageText, d2.messageText) || 0; } export function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] { if (diagnostics.length < 2) { return diagnostics; } var newDiagnostics = [diagnostics[0]]; var previousDiagnostic = diagnostics[0]; for (var i = 1; i < diagnostics.length; i++) { var currentDiagnostic = diagnostics[i]; var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0; if (!isDupe) { newDiagnostics.push(currentDiagnostic); previousDiagnostic = currentDiagnostic; } } return newDiagnostics; } export function normalizeSlashes(path: string): string { return path.replace(/\\/g, "/"); } // Returns length of path root (i.e. length of "/", "x:/", "//server/share/") export function getRootLength(path: string): number { if (path.charCodeAt(0) === CharacterCodes.slash) { if (path.charCodeAt(1) !== CharacterCodes.slash) return 1; var p1 = path.indexOf("/", 2); if (p1 < 0) return 2; var p2 = path.indexOf("/", p1 + 1); if (p2 < 0) return p1 + 1; return p2 + 1; } if (path.charCodeAt(1) === CharacterCodes.colon) { if (path.charCodeAt(2) === CharacterCodes.slash) return 3; return 2; } return 0; } export var directorySeparator = "/"; function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { var parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); var normalized: string[] = []; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part !== ".") { if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { normalized.pop(); } else { normalized.push(part); } } } return normalized; } export function normalizePath(path: string): string { var path = normalizeSlashes(path); var rootLength = getRootLength(path); var normalized = getNormalizedParts(path, rootLength); return path.substr(0, rootLength) + normalized.join(directorySeparator); } export function getDirectoryPath(path: string) { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator))); } export function isUrl(path: string) { return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } export function isRootedDiskPath(path: string) { return getRootLength(path) !== 0; } function normalizedPathComponents(path: string, rootLength: number) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); } export function getNormalizedPathComponents(path: string, currentDirectory: string) { var path = normalizeSlashes(path); var rootLength = getRootLength(path); if (rootLength == 0) { // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); } return normalizedPathComponents(path, rootLength); } export function getNormalizedPathFromPathCompoments(pathComponents: string[]) { if (pathComponents && pathComponents.length) { return pathComponents[0] + pathComponents.slice(1).join(directorySeparator); } } function getNormalizedPathComponentsOfUrl(url: string) { // Get root length of http://www.website.com/folder1/foler2/ // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part var rootLength = url.indexOf("://") + "://".length; while (rootLength < urlLength) { // Consume all immediate slashes in the protocol // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// if (url.charCodeAt(rootLength) === CharacterCodes.slash) { rootLength++; } else { // non slash character means we continue proceeding to next component of root search break; } } // there are no parts after http:// just return current string as the pathComponent if (rootLength === urlLength) { return [url]; } // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) var indexOfNextSlash = url.indexOf(directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ // and get components afetr the root normally like any other folder components rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } else { // Can't find the host assume the rest of the string as component // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + directorySeparator]; } } function getNormalizedPathOrUrlComponents(pathOrUrl: string, currentDirectory: string) { if (isUrl(pathOrUrl)) { return getNormalizedPathComponentsOfUrl(pathOrUrl); } else { return getNormalizedPathComponents(pathOrUrl, currentDirectory); } } export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, isAbsolutePathAnUrl: boolean) { var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { // If the directory path given was of type test/cases/ then we really need components of directry to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.length--; } // Find the component that differs for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (directoryComponents[joinStartIndex] !== pathComponents[joinStartIndex]) { break; } } // Get the relative path if (joinStartIndex) { var relativePath = ""; var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { if (directoryComponents[joinStartIndex] !== "") { relativePath = relativePath + ".." + directorySeparator; } } return relativePath + relativePathComponents.join(directorySeparator); } // Cant find the relative path, get the absolute path var absolutePath = getNormalizedPathFromPathCompoments(pathComponents); if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { absolutePath = "file:///" + absolutePath; } return absolutePath; } export function getBaseFilename(path: string) { var i = path.lastIndexOf(directorySeparator); return i < 0 ? path : path.substring(i + 1); } export function combinePaths(path1: string, path2: string) { if (!(path1 && path1.length)) return path2; if (!(path2 && path2.length)) return path1; if (path2.charAt(0) === directorySeparator) return path2; if (path1.charAt(path1.length - 1) === directorySeparator) return path1 + path2; return path1 + directorySeparator + path2; } export function fileExtensionIs(path: string, extension: string): boolean { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } export function getCanonicalFileName(fileName: string): string { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } export interface ObjectAllocator { getNodeConstructor(kind: SyntaxKind): new () => Node; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; getSignatureConstructor(): new (checker: TypeChecker) => Signature; } function Symbol(flags: SymbolFlags, name: string) { this.flags = flags; this.name = name; this.declarations = undefined; } function Type(checker: TypeChecker, flags: TypeFlags) { this.flags = flags; } function Signature(checker: TypeChecker) { } export var objectAllocator: ObjectAllocator = { getNodeConstructor: kind => { function Node() { } Node.prototype = { kind: kind, pos: 0, end: 0, flags: 0, parent: undefined, }; return <any>Node; }, getSymbolConstructor: () => <any>Symbol, getTypeConstructor: () => <any>Type, getSignatureConstructor: () => <any>Signature } export enum AssertionLevel { None = 0, Normal = 1, Aggressive = 2, VeryAggressive = 3, } export module Debug { var currentAssertionLevel = AssertionLevel.None; export function shouldAssert(level: AssertionLevel): boolean { return this.currentAssertionLevel >= level; } export function assert(expression: any, message?: string, verboseDebugInfo?: () => string): void { if (!expression) { var verboseDebugString = ""; if (verboseDebugInfo) { verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); } throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); } } export function fail(message?: string): void { Debug.assert(false, message); } } }
src/compiler/core.ts
1
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.005532063078135252, 0.0006127195083536208, 0.00016159478400368243, 0.00017325428780168295, 0.0011528898030519485 ]
{ "id": 1, "code_window": [ " var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, chainedMessage, terminalMessage);\n", " if (overflow) {\n", " error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));\n", " }\n", " else if (errorInfo) {\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));\n", " }\n", " return result;\n", "\n", " function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1047 }
//@module: amd class Foo { public get foo() { var i: Foo; return i; // Should be fine (previous bug report visibility error). } } export var x = 5;
tests/cases/compiler/exportingContainingVisibleType.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017414387548342347, 0.00017146764730568975, 0.00016879141912795603, 0.00017146764730568975, 0.0000026762281777337193 ]
{ "id": 1, "code_window": [ " var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, chainedMessage, terminalMessage);\n", " if (overflow) {\n", " error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));\n", " }\n", " else if (errorInfo) {\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));\n", " }\n", " return result;\n", "\n", " function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1047 }
//// [typeofUndefined.ts] var x: typeof undefined; var x: any; // shouldn't be an error since type is the same as the first declaration //// [typeofUndefined.js] var x; var x; //// [typeofUndefined.d.ts] declare var x: any; declare var x: any;
tests/baselines/reference/typeofUndefined.js
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.0001703770540188998, 0.00016895760199986398, 0.00016753814998082817, 0.00016895760199986398, 0.0000014194520190358162 ]
{ "id": 1, "code_window": [ " var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, chainedMessage, terminalMessage);\n", " if (overflow) {\n", " error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));\n", " }\n", " else if (errorInfo) {\n", " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));\n", " }\n", " return result;\n", "\n", " function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine()));\n" ], "file_path": "src/compiler/checker.ts", "type": "replace", "edit_start_line_idx": 1047 }
{ "scenario": "[Sourcemap]/[Maproot-AbsolutePath]: outputdir_singleFile: specify outputFile", "projectRoot": "tests/cases/projects/outputdir_singleFile", "inputFiles": [ "test.ts" ], "out": "bin/test.js", "sourceMap": true, "mapRoot": "tests/cases/projects/outputdir_singleFile/mapFiles", "resolveMapRoot": true, "declaration": true, "baselineCheck": true, "resolvedInputFiles": [ "test.ts", "lib.d.ts" ], "emittedFiles": [ "bin/test.js.map", "bin/test.js", "bin/test.d.ts" ] }
tests/baselines/reference/project/mapRootAbsolutePathSingleFileSpecifyOutputFile/node/mapRootAbsolutePathSingleFileSpecifyOutputFile.json
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017844323883764446, 0.00017379179189447314, 0.00016826514911372215, 0.0001746670313877985, 0.000004201022875349736 ]
{ "id": 2, "code_window": [ " next: details\n", " }\n", " }\n", "\n", " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain): Diagnostic {\n", " var code = diagnosticChain.code;\n", " var category = diagnosticChain.category;\n", " var messageText = \"\";\n", "\n", " var indent = 0;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain, newLine: string): Diagnostic {\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 216 }
/// <reference path="core.ts"/> /// <reference path="sys.ts"/> /// <reference path="types.ts"/> /// <reference path="scanner.ts"/> /// <reference path="parser.ts"/> /// <reference path="binder.ts"/> /// <reference path="checker.ts"/> /// <reference path="emitter.ts"/> /// <reference path="commandLineParser.ts"/> module ts { /// Checks to see if the locale is in the appropriate format, /// and if it is, attempt to set the appropriate language. function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean { var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp')); return false; } var language = matchResult[1]; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. if (!trySetLanguageAndTerritory(language, territory, errors) && !trySetLanguageAndTerritory(language, undefined, errors)) { errors.push(createCompilerDiagnostic(Diagnostics.Unsupported_locale_0, locale)); return false; } return true; } function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean { var compilerFilePath = sys.getExecutingFilePath(); var containingDirectoryPath = getDirectoryPath(compilerFilePath); var filePath = combinePaths(containingDirectoryPath, language); if (territory) { filePath = filePath + "-" + territory; } filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json")); if (!sys.fileExists(filePath)) { return false; } // TODO: Add codePage support for readFile? try { var fileContents = sys.readFile(filePath); } catch (e) { errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); return false; } try { localizedDiagnosticMessages = JSON.parse(fileContents); } catch (e) { errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath)); return false; } return true; } function countLines(program: Program): number { var count = 0; forEach(program.getSourceFiles(), file => { count += file.getLineAndCharacterFromPosition(file.end).line; }); return count; } function reportErrors(errors: Diagnostic[]) { for (var i = 0; i < errors.length; i++) { var error = errors[i]; if (error.file) { var loc = error.file.getLineAndCharacterFromPosition(error.start); sys.writeErr(error.file.filename + "(" + loc.line + "," + loc.character + "): " + error.messageText + sys.newLine); } else { sys.writeErr(error.messageText + sys.newLine); } } } function padLeft(s: string, length: number) { while (s.length < length) s = " " + s; return s; } function padRight(s: string, length: number) { while (s.length < length) s = s + " "; return s; } function reportDiagnostic(name: string, value: string) { sys.writeErr(padRight(name + ":", 12) + padLeft(value.toString(), 10) + sys.newLine); } function reportDiagnosticCount(name: string, count: number) { reportDiagnostic(name, "" + count); } function reportDiagnosticTime(name: string, time: number) { reportDiagnostic(name, (time / 1000).toFixed(2) + "s"); } function createCompilerHost(options: CompilerOptions): CompilerHost { var currentDirectory: string; var existingDirectories: Map<boolean> = {}; function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { try { var text = sys.readFile(filename, options.charset); } catch (e) { if (onError) onError(e.message); text = ""; } return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined; } function writeFile(fileName: string, data: string, onError?: (message: string) => void) { function directoryExists(directoryPath: string): boolean { if (hasProperty(existingDirectories, directoryPath)) { return true; } if (sys.directoryExists(directoryPath)) { existingDirectories[directoryPath] = true; return true; } return false; } function ensureDirectoriesExist(directoryPath: string) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); sys.createDirectory(directoryPath); } } try { ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data); } catch (e) { if (onError) onError(e.message); } } return { getSourceFile: getSourceFile, getDefaultLibFilename: () => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), "lib.d.ts"), writeFile: writeFile, getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, getCanonicalFileName: getCanonicalFileName }; } export function executeCommandLine(args: string[]): number { var cmds = parseCommandLine(args); if (cmds.filenames.length === 0 && !(cmds.options.help || cmds.options.version)) { cmds.errors.push(createCompilerDiagnostic(Diagnostics.No_input_files_specified)); } if (cmds.options.version) { } if (cmds.filenames.length === 0 || cmds.options.help) { // TODO (drosen): Usage. } // If a locale has been set but fails to load, act as if it was never specified, // but collect the errors to report along the way. if (cmds.options.locale) { validateLocaleAndSetLanguage(cmds.options.locale, cmds.errors); } if (cmds.errors.length) { reportErrors(cmds.errors); return 1; } var parseStart = new Date().getTime(); var program = createProgram(cmds.filenames, cmds.options, createCompilerHost(cmds.options)); var bindStart = new Date().getTime(); var errors = program.getDiagnostics(); if (errors.length) { var checkStart = bindStart; var emitStart = bindStart; var reportStart = bindStart; } else { var checker = program.getTypeChecker(); var checkStart = new Date().getTime(); var semanticErrors = checker.getDiagnostics(); var emitStart = new Date().getTime(); var emitErrors = checker.emitFiles().errors; var reportStart = new Date().getTime(); errors = concatenate(semanticErrors, emitErrors); } reportErrors(errors); if (cmds.options.diagnostics) { reportDiagnosticCount("Files", program.getSourceFiles().length); reportDiagnosticCount("Lines", countLines(program)); reportDiagnosticCount("Nodes", checker ? checker.getNodeCount() : 0); reportDiagnosticCount("Identifiers", checker ? checker.getIdentifierCount() : 0); reportDiagnosticCount("Symbols", checker ? checker.getSymbolCount() : 0); reportDiagnosticCount("Types", checker ? checker.getTypeCount() : 0); reportDiagnosticTime("Parse time", bindStart - parseStart); reportDiagnosticTime("Bind time", checkStart - bindStart); reportDiagnosticTime("Check time", emitStart - checkStart); reportDiagnosticTime("Emit time", reportStart - emitStart); reportDiagnosticTime("Total time", reportStart - parseStart); } return errors.length ? 1 : 0; } } sys.exit(ts.executeCommandLine(sys.args));
src/compiler/tc.ts
1
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.8380340933799744, 0.07029090076684952, 0.00016813140246085823, 0.004416572395712137, 0.2056163102388382 ]
{ "id": 2, "code_window": [ " next: details\n", " }\n", " }\n", "\n", " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain): Diagnostic {\n", " var code = diagnosticChain.code;\n", " var category = diagnosticChain.category;\n", " var messageText = \"\";\n", "\n", " var indent = 0;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain, newLine: string): Diagnostic {\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 216 }
//// [global.ts] module M { export function f(y:number) { return x+y; } } var x=10; M.f(3); //// [global.js] var M; (function (M) { function f(y) { return x + y; } M.f = f; })(M || (M = {})); var x = 10; M.f(3);
tests/baselines/reference/global.js
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017441838281229138, 0.00017090636538341641, 0.00016838456213008612, 0.0001699161366559565, 0.0000025608794658182887 ]
{ "id": 2, "code_window": [ " next: details\n", " }\n", " }\n", "\n", " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain): Diagnostic {\n", " var code = diagnosticChain.code;\n", " var category = diagnosticChain.category;\n", " var messageText = \"\";\n", "\n", " var indent = 0;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain, newLine: string): Diagnostic {\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 216 }
// no errors expected class C<T extends Date> { constructor(public data: T) { } foo<U extends T>(x: U) { return x; } } interface Foo extends Date { foo: string; } var y: Foo = null; var c = new C(y); var r = c.foo(y);
tests/cases/conformance/types/typeParameters/typeArgumentLists/wrappedAndRecursiveConstraints.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017151936481241137, 0.00016909552505239844, 0.00016667168529238552, 0.00016909552505239844, 0.0000024238397600129247 ]
{ "id": 2, "code_window": [ " next: details\n", " }\n", " }\n", "\n", " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain): Diagnostic {\n", " var code = diagnosticChain.code;\n", " var category = diagnosticChain.category;\n", " var messageText = \"\";\n", "\n", " var indent = 0;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain, newLine: string): Diagnostic {\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 216 }
//// [ExportInterfaceWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.ts] module A { export interface Point { x: number; y: number; } export var Origin: Point = { x: 0, y: 0 }; export interface Point3d extends Point { z: number; } export var Origin3d: Point3d = { x: 0, y: 0, z: 0 }; export interface Line<TPoint extends Point>{ new (start: TPoint, end: TPoint); start: TPoint; end: TPoint; } } //// [ExportInterfaceWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js] var A; (function (A) { A.Origin = { x: 0, y: 0 }; A.Origin3d = { x: 0, y: 0, z: 0 }; })(A || (A = {}));
tests/baselines/reference/ExportInterfaceWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.0005768800037913024, 0.0003446333867032081, 0.00016917007451411337, 0.00031624172697775066, 0.00014734151773154736 ]
{ "id": 3, "code_window": [ "\n", " var indent = 0;\n", " while (diagnosticChain) {\n", " if (indent) {\n", " messageText += sys.newLine;\n", " \n", " for (var i = 0; i < indent; i++) {\n", " messageText += \" \";\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " messageText += newLine;\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 224 }
/// <reference path="core.ts"/> /// <reference path="scanner.ts"/> module ts { export interface TextRange { pos: number; end: number; } // token > SyntaxKind.Identifer => token is a keyword export enum SyntaxKind { Unknown, EndOfFileToken, // Literals NumericLiteral, StringLiteral, RegularExpressionLiteral, // Punctuation OpenBraceToken, CloseBraceToken, OpenParenToken, CloseParenToken, OpenBracketToken, CloseBracketToken, DotToken, DotDotDotToken, SemicolonToken, CommaToken, LessThanToken, GreaterThanToken, LessThanEqualsToken, GreaterThanEqualsToken, EqualsEqualsToken, ExclamationEqualsToken, EqualsEqualsEqualsToken, ExclamationEqualsEqualsToken, EqualsGreaterThanToken, PlusToken, MinusToken, AsteriskToken, SlashToken, PercentToken, PlusPlusToken, MinusMinusToken, LessThanLessThanToken, GreaterThanGreaterThanToken, GreaterThanGreaterThanGreaterThanToken, AmpersandToken, BarToken, CaretToken, ExclamationToken, TildeToken, AmpersandAmpersandToken, BarBarToken, QuestionToken, ColonToken, // Assignments EqualsToken, PlusEqualsToken, MinusEqualsToken, AsteriskEqualsToken, SlashEqualsToken, PercentEqualsToken, LessThanLessThanEqualsToken, GreaterThanGreaterThanEqualsToken, GreaterThanGreaterThanGreaterThanEqualsToken, AmpersandEqualsToken, BarEqualsToken, CaretEqualsToken, // Identifiers Identifier, // Reserved words BreakKeyword, CaseKeyword, CatchKeyword, ClassKeyword, ConstKeyword, ContinueKeyword, DebuggerKeyword, DefaultKeyword, DeleteKeyword, DoKeyword, ElseKeyword, EnumKeyword, ExportKeyword, ExtendsKeyword, FalseKeyword, FinallyKeyword, ForKeyword, FunctionKeyword, IfKeyword, ImportKeyword, InKeyword, InstanceOfKeyword, NewKeyword, NullKeyword, ReturnKeyword, SuperKeyword, SwitchKeyword, ThisKeyword, ThrowKeyword, TrueKeyword, TryKeyword, TypeOfKeyword, VarKeyword, VoidKeyword, WhileKeyword, WithKeyword, // Strict mode reserved words ImplementsKeyword, InterfaceKeyword, LetKeyword, PackageKeyword, PrivateKeyword, ProtectedKeyword, PublicKeyword, StaticKeyword, YieldKeyword, // TypeScript keywords AnyKeyword, BooleanKeyword, ConstructorKeyword, DeclareKeyword, GetKeyword, ModuleKeyword, RequireKeyword, NumberKeyword, SetKeyword, StringKeyword, // Parse tree nodes Missing, // Names QualifiedName, // Signature elements TypeParameter, Parameter, // TypeMember Property, Method, Constructor, GetAccessor, SetAccessor, CallSignature, ConstructSignature, IndexSignature, // Type TypeReference, TypeQuery, TypeLiteral, ArrayType, // Expression ArrayLiteral, ObjectLiteral, PropertyAssignment, PropertyAccess, IndexedAccess, CallExpression, NewExpression, TypeAssertion, ParenExpression, FunctionExpression, ArrowFunction, PrefixOperator, PostfixOperator, BinaryExpression, ConditionalExpression, OmittedExpression, // Element Block, VariableStatement, EmptyStatement, ExpressionStatement, IfStatement, DoStatement, WhileStatement, ForStatement, ForInStatement, ContinueStatement, BreakStatement, ReturnStatement, WithStatement, SwitchStatement, CaseClause, DefaultClause, LabelledStatement, ThrowStatement, TryStatement, TryBlock, CatchBlock, FinallyBlock, DebuggerStatement, VariableDeclaration, FunctionDeclaration, FunctionBlock, ClassDeclaration, InterfaceDeclaration, EnumDeclaration, ModuleDeclaration, ModuleBlock, ImportDeclaration, ExportAssignment, // Enum EnumMember, // Top-level nodes SourceFile, Program, // Synthesized list SyntaxList, // Enum value count Count, // Markers FirstAssignment = EqualsToken, LastAssignment = CaretEqualsToken, FirstReservedWord = BreakKeyword, LastReservedWord = WithKeyword, FirstKeyword = BreakKeyword, LastKeyword = StringKeyword, FirstFutureReservedWord = ImplementsKeyword, LastFutureReservedWord = YieldKeyword } export enum NodeFlags { Export = 0x00000001, // Declarations Ambient = 0x00000002, // Declarations QuestionMark = 0x00000004, // Parameter/Property/Method Rest = 0x00000008, // Parameter Public = 0x00000010, // Property/Method Private = 0x00000020, // Property/Method Static = 0x00000040, // Property/Method MultiLine = 0x00000080, // Multi-line array or object literal Synthetic = 0x00000100, // Synthetic node (for full fidelity) DeclarationFile = 0x00000200, // Node is a .d.ts file Modifier = Export | Ambient | Public | Private | Static } export interface Node extends TextRange { kind: SyntaxKind; flags: NodeFlags; id?: number; // Unique id (used to look up NodeLinks) parent?: Node; // Parent node (initialized by binding) symbol?: Symbol; // Symbol declared by node (initialized by binding) locals?: SymbolTable; // Locals associated with node (initialized by binding) nextContainer?: Node; // Next container in declaration order (initialized by binding) localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes) } export interface NodeArray<T> extends Array<T>, TextRange { } export interface Identifier extends Node { text: string; // Text of identifier (with escapes converted to characters) } export interface QualifiedName extends Node { // Must have same layout as PropertyAccess left: EntityName; right: Identifier; } export interface EntityName extends Node { // Identifier, QualifiedName, or Missing } export interface ParsedSignature { typeParameters?: NodeArray<TypeParameterDeclaration>; parameters: NodeArray<ParameterDeclaration>; type?: TypeNode; } export interface Declaration extends Node { name?: Identifier; } export interface TypeParameterDeclaration extends Declaration { constraint?: TypeNode; } export interface SignatureDeclaration extends Declaration, ParsedSignature { } export interface VariableDeclaration extends Declaration { type?: TypeNode; initializer?: Expression; } export interface PropertyDeclaration extends VariableDeclaration { } export interface ParameterDeclaration extends VariableDeclaration { } export interface FunctionDeclaration extends Declaration, ParsedSignature { body?: Node; // Block or Expression } export interface MethodDeclaration extends FunctionDeclaration { } export interface ConstructorDeclaration extends FunctionDeclaration { } export interface AccessorDeclaration extends FunctionDeclaration { } export interface TypeNode extends Node { } export interface TypeReferenceNode extends TypeNode { typeName: EntityName; typeArguments?: NodeArray<TypeNode>; } export interface TypeQueryNode extends TypeNode { exprName: EntityName; } export interface TypeLiteralNode extends TypeNode { members: NodeArray<Node>; } export interface ArrayTypeNode extends TypeNode { elementType: TypeNode; } export interface StringLiteralTypeNode extends TypeNode { text: string; } export interface Expression extends Node { } export interface UnaryExpression extends Expression { operator: SyntaxKind; operand: Expression; } export interface BinaryExpression extends Expression { left: Expression; operator: SyntaxKind; right: Expression; } export interface ConditionalExpression extends Expression { condition: Expression; whenTrue: Expression; whenFalse: Expression; } export interface FunctionExpression extends Expression, FunctionDeclaration { body: Node; // Required, whereas the member inherited from FunctionDeclaration is optional } // The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral // this means quotes have been removed and escapes have been converted to actual characters. For a NumericLiteral, the // stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1". export interface LiteralExpression extends Expression { text: string; } export interface ParenExpression extends Expression { expression: Expression; } export interface ArrayLiteral extends Expression { elements: NodeArray<Expression>; } export interface ObjectLiteral extends Expression { properties: NodeArray<Node>; } export interface PropertyAccess extends Expression { left: Expression; right: Identifier; } export interface IndexedAccess extends Expression { object: Expression; index: Expression; } export interface CallExpression extends Expression { func: Expression; typeArguments?: NodeArray<TypeNode>; arguments: NodeArray<Expression>; } export interface NewExpression extends CallExpression { } export interface TypeAssertion extends Expression { type: TypeNode; operand: Expression; } export interface Statement extends Node { } export interface Block extends Statement { statements: NodeArray<Statement>; } export interface VariableStatement extends Statement { declarations: NodeArray<VariableDeclaration>; } export interface ExpressionStatement extends Statement { expression: Expression; } export interface IfStatement extends Statement { expression: Expression; thenStatement: Statement; elseStatement?: Statement; } export interface IterationStatement extends Statement { statement: Statement; } export interface DoStatement extends IterationStatement { expression: Expression; } export interface WhileStatement extends IterationStatement { expression: Expression; } export interface ForStatement extends IterationStatement { declarations?: NodeArray<VariableDeclaration>; initializer?: Expression; condition?: Expression; iterator?: Expression; } export interface ForInStatement extends IterationStatement { declaration?: VariableDeclaration; variable?: Expression; expression: Expression; } export interface BreakOrContinueStatement extends Statement { label?: Identifier; } export interface ReturnStatement extends Statement { expression?: Expression; } export interface WithStatement extends Statement { expression: Expression; statement: Statement; } export interface SwitchStatement extends Statement { expression: Expression; clauses: NodeArray<CaseOrDefaultClause>; } export interface CaseOrDefaultClause extends Node { expression?: Expression; statements: NodeArray<Statement>; } export interface LabelledStatement extends Statement { label: Identifier; statement: Statement; } export interface ThrowStatement extends Statement { expression: Expression; } export interface TryStatement extends Statement { tryBlock: Block; catchBlock?: CatchBlock; finallyBlock?: Block; } export interface CatchBlock extends Block { variable: Identifier; } export interface ClassDeclaration extends Declaration { typeParameters?: NodeArray<TypeParameterDeclaration>; baseType?: TypeReferenceNode; implementedTypes?: NodeArray<TypeReferenceNode>; members: NodeArray<Node>; } export interface InterfaceDeclaration extends Declaration { typeParameters?: NodeArray<TypeParameterDeclaration>; baseTypes?: NodeArray<TypeReferenceNode>; members: NodeArray<Node>; } export interface EnumMember extends Declaration { initializer?: Expression; } export interface EnumDeclaration extends Declaration { members: NodeArray<EnumMember>; } export interface ModuleDeclaration extends Declaration { body: Node; // Block or ModuleDeclaration } export interface ImportDeclaration extends Declaration { entityName?: EntityName; externalModuleName?: LiteralExpression; } export interface ExportAssignment extends Statement { exportName: Identifier; } export interface FileReference extends TextRange { filename: string; } export interface SourceFile extends Block { filename: string; text: string; getLineAndCharacterFromPosition(position: number): { line: number; character: number }; amdDependencies: string[]; referencedFiles: FileReference[]; syntacticErrors: Diagnostic[]; semanticErrors: Diagnostic[]; hasNoDefaultLib: boolean; externalModuleIndicator: Node; // The first node that causes this file to be an external module nodeCount: number; identifierCount: number; symbolCount: number; } export interface Program { getSourceFile(filename: string): SourceFile; getSourceFiles(): SourceFile[]; getCompilerOptions(): CompilerOptions; getCompilerHost(): CompilerHost; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getTypeChecker(): TypeChecker; getCommonSourceDirectory(): string; } export interface SourceMapSpan { /** Line number in the js file*/ emittedLine: number; /** Column number in the js file */ emittedColumn: number; /** Line number in the ts file */ sourceLine: number; /** Column number in the ts file */ sourceColumn: number; /** Optional name (index into names array) associated with this span */ nameIndex?: number; /** ts file (index into sources array) associated with this span*/ sourceIndex: number; } export interface SourceMapData { /** Where the sourcemap file is written */ sourceMapFilePath: string; /** source map url written in the js file */ jsSourceMappingURL: string; /** Source map's file field - js file name*/ sourceMapFile: string; /** Source map's sourceRoot field - location where the sources will be present if not "" */ sourceMapSourceRoot: string; /** Source map's sources field - list of sources that can be indexed in this source map*/ sourceMapSources: string[]; /** input source file (which one can use on program to get the file) this is one to one mapping with the sourceMapSources list*/ inputSourceFileNames: string[]; /** Source map's names field - list of names that can be indexed in this source map*/ sourceMapNames?: string[]; /** Source map's mapping field - encoded source map spans*/ sourceMapMappings: string; /** Raw source map spans that were encoded into the sourceMapMappings*/ sourceMapDecodedMappings: SourceMapSpan[]; } export interface EmitResult { errors: Diagnostic[]; sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps } export interface TypeChecker { getProgram(): Program; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; getTypeCount(): number; checkProgram(): void; emitFiles(): EmitResult; getSymbolOfNode(node: Node): Symbol; getParentOfSymbol(symbol: Symbol): Symbol; getTypeOfSymbol(symbol: Symbol): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; getIndexTypeOfType(type: Type, kind: IndexKind): Type; getReturnTypeOfSignature(signature: Signature): Type; resolveEntityName(location: Node, name: EntityName, meaning: SymbolFlags): Symbol; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolOfIdentifier(identifier: Identifier): Symbol; } export interface TextWriter { write(s: string): void; writeLine(): void; increaseIndent(): void; decreaseIndent(): void; getText(): string; } export enum TypeFormatFlags { None = 0x00000000, /** writes Array<T> instead T[] */ WriteArrayAsGenericType = 0x00000001, // Declarations } export interface EmitResolver { getProgram(): Program; getLocalNameOfContainer(container: Declaration): string; getExpressionNamePrefix(node: Identifier): string; getPropertyAccessSubstitution(node: PropertyAccess): string; getExportAssignmentName(node: SourceFile): string; isReferencedImportDeclaration(node: ImportDeclaration): boolean; isTopLevelValueImportedViaEntityName(node: ImportDeclaration): boolean; getNodeCheckFlags(node: Node): NodeCheckFlags; getEnumMemberValue(node: EnumMember): number; shouldEmitDeclarations(): boolean; isDeclarationVisible(node: Declaration): boolean; isImplementationOfOverload(node: FunctionDeclaration): boolean; writeTypeAtLocation(location: Node, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter): void; writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter): void; } export enum SymbolFlags { Variable = 0x00000001, // Variable or parameter Property = 0x00000002, // Property or enum member EnumMember = 0x00000004, // Enum member Function = 0x00000008, // Function Class = 0x00000010, // Class Interface = 0x00000020, // Interface Enum = 0x00000040, // Enum ValueModule = 0x00000080, // Instantiated module NamespaceModule = 0x00000100, // Uninstantiated module TypeLiteral = 0x00000200, // Type Literal ObjectLiteral = 0x00000400, // Object Literal Method = 0x00000800, // Method Constructor = 0x00001000, // Constructor GetAccessor = 0x00002000, // Get accessor SetAccessor = 0x00004000, // Set accessor CallSignature = 0x00008000, // Call signature ConstructSignature = 0x00010000, // Construct signature IndexSignature = 0x00020000, // Index signature TypeParameter = 0x00040000, // Type parameter // Export markers (see comment in declareModuleMember in binder) ExportValue = 0x00080000, // Exported value marker ExportType = 0x00100000, // Exported type marker ExportNamespace = 0x00200000, // Exported namespace marker Import = 0x00400000, // Import Instantiated = 0x00800000, // Instantiated symbol Merged = 0x01000000, // Merged symbol (created during program binding) Transient = 0x02000000, // Transient symbol (created during type check) Prototype = 0x04000000, // Symbol for the prototype property (without source code representation) Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor, Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter, Namespace = ValueModule | NamespaceModule, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, Signature = CallSignature | ConstructSignature | IndexSignature, ParameterExcludes = Value, VariableExcludes = Value & ~Variable, PropertyExcludes = Value, EnumMemberExcludes = Value, FunctionExcludes = Value & ~(Function | ValueModule), ClassExcludes = (Value | Type) & ~ValueModule, InterfaceExcludes = Type & ~Interface, EnumExcludes = (Value | Type) & ~(Enum | ValueModule), ValueModuleExcludes = Value & ~(Function | Class | Enum | ValueModule), NamespaceModuleExcludes = 0, MethodExcludes = Value & ~Method, GetAccessorExcludes = Value & ~SetAccessor, SetAccessorExcludes = Value & ~GetAccessor, TypeParameterExcludes = Type & ~TypeParameter, // Imports collide with all other imports with the same name. ImportExcludes = Import, ModuleMember = Variable | Function | Class | Interface | Enum | Module | Import, ExportHasLocal = Function | Class | Enum | ValueModule, HasLocals = Function | Module | Method | Constructor | Accessor | Signature, HasExports = Class | Enum | Module, HasMembers = Class | Interface | TypeLiteral | ObjectLiteral, IsContainer = HasLocals | HasExports | HasMembers, PropertyOrAccessor = Property | Accessor, Export = ExportNamespace | ExportType | ExportValue, } export interface Symbol { flags: SymbolFlags; // Symbol flags name: string; // Name of symbol id?: number; // Unique id (used to look up SymbolLinks) mergeId?: number; // Merge id (used to look up merged symbol) declarations?: Declaration[]; // Declarations associated with this symbol parent?: Symbol; // Parent symbol members?: SymbolTable; // Class, interface or literal instance members exports?: SymbolTable; // Module exports exportSymbol?: Symbol; // Exported symbol associated with this symbol exportAssignSymbol?: Symbol; // Symbol exported from external module valueDeclaration?: Declaration // First value declaration of the symbol } export interface SymbolLinks { target?: Symbol; // Resolved (non-alias) target of an alias type?: Type; // Type of value symbol declaredType?: Type; // Type of class, interface, enum, or type parameter mapper?: TypeMapper; // Type mapper for instantiation alias referenced?: boolean; // True if alias symbol has been referenced as a value } export interface TransientSymbol extends Symbol, SymbolLinks { } export interface SymbolTable { [index: string]: Symbol; } export enum NodeCheckFlags { TypeChecked = 0x00000001, // Node has been type checked LexicalThis = 0x00000002, // Lexical 'this' reference CaptureThis = 0x00000004, // Lexical 'this' used in body EmitExtends = 0x00000008, // Emit __extends SuperInstance = 0x00000010, // Instance 'super' reference SuperStatic = 0x00000020, // Static 'super' reference } export interface NodeLinks { resolvedType?: Type; // Cached type of type node resolvedSignature?: Signature; // Cached signature of signature node resolvedSymbol?: Symbol; // Cached name resolution result flags?: NodeCheckFlags; // Set of flags specific to Node enumMemberValue?: number; // Constant value of enum member isIllegalTypeReferenceInConstraint?: boolean; // Is type reference in constraint refers to the type parameter from the same list isVisible?: boolean; // Is this node visible localModuleName?: string; // Local name for module instance } export enum TypeFlags { Any = 0x00000001, String = 0x00000002, Number = 0x00000004, Boolean = 0x00000008, Void = 0x00000010, Undefined = 0x00000020, Null = 0x00000040, Enum = 0x00000080, // Enum type StringLiteral = 0x00000100, // String literal type TypeParameter = 0x00000200, // Type parameter Class = 0x00000400, // Class Interface = 0x00000800, // Interface Reference = 0x00001000, // Generic type reference Anonymous = 0x00002000, // Anonymous FromSignature = 0x00004000, // Created for signature assignment check Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null, StringLike = String | StringLiteral, NumberLike = Number | Enum, ObjectType = Class | Interface | Reference | Anonymous } // Properties common to all types export interface Type { flags: TypeFlags; // Flags id: number; // Unique ID symbol?: Symbol; // Symbol associated with type (if any) } // Intrinsic types (TypeFlags.Intrinsic) export interface IntrinsicType extends Type { intrinsicName: string; // Name of intrinsic type } // String literal types (TypeFlags.StringLiteral) export interface StringLiteralType extends Type { text: string; // Text of string literal } // Object types (TypeFlags.ObjectType) export interface ObjectType extends Type { } export interface ApparentType extends Type { // This property is not used. It is just to make the type system think ApparentType // is a strict subtype of Type. _apparentTypeBrand: any; } // Class and interface types (TypeFlags.Class and TypeFlags.Interface) export interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) baseTypes: ObjectType[]; // Base types declaredProperties: Symbol[]; // Declared members declaredCallSignatures: Signature[]; // Declared call signatures declaredConstructSignatures: Signature[]; // Declared construct signatures declaredStringIndexType: Type; // Declared string index type declaredNumberIndexType: Type; // Declared numeric index type } // Type references (TypeFlags.Reference) export interface TypeReference extends ObjectType { target: GenericType; // Type reference target typeArguments: Type[]; // Type reference type arguments } // Generic class and interface types export interface GenericType extends InterfaceType, TypeReference { instantiations: Map<TypeReference>; // Generic instantiation cache openReferenceTargets: GenericType[]; // Open type reference targets openReferenceChecks: Map<boolean>; // Open type reference check cache } // Resolved object type export interface ResolvedObjectType extends ObjectType { members: SymbolTable; // Properties by name properties: Symbol[]; // Properties callSignatures: Signature[]; // Call signatures of type constructSignatures: Signature[]; // Construct signatures of type stringIndexType: Type; // String index type numberIndexType: Type; // Numeric index type } // Type parameters (TypeFlags.TypeParameter) export interface TypeParameter extends Type { constraint: Type; // Constraint target?: TypeParameter; // Instantiation target mapper?: TypeMapper; // Instantiation mapper } export enum SignatureKind { Call, Construct, } export interface Signature { declaration: SignatureDeclaration; // Originating declaration typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters resolvedReturnType: Type; // Resolved return type minArgumentCount: number; // Number of non-optional parameters hasRestParameter: boolean; // True if last parameter is rest parameter hasStringLiterals: boolean; // True if instantiated target?: Signature; // Instantiation target mapper?: TypeMapper; // Instantiation mapper erasedSignatureCache?: Signature; // Erased version of signature (deferred) isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison } export enum IndexKind { String, Number, } export interface TypeMapper { (t: Type): Type; } export interface InferenceContext { typeParameters: TypeParameter[]; inferences: Type[][]; inferredTypes: Type[]; } export interface DiagnosticMessage { key: string; category: DiagnosticCategory; code: number; } // A linked list of formatted diagnostic messages to be used as part of a multiline message. // It is built from the bottom up, leaving the head to be the "main" diagnostic. // While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, // the difference is that messages are all preformatted in DMC. export interface DiagnosticMessageChain { messageText: string; category: DiagnosticCategory; code: number; next?: DiagnosticMessageChain; } export interface Diagnostic { file: SourceFile; start: number; length: number; messageText: string; category: DiagnosticCategory; code: number; } export enum DiagnosticCategory { Warning, Error, Message, NoPrefix } export interface CompilerOptions { charset?: string; codepage?: number; declaration?: boolean; diagnostics?: boolean; help?: boolean; locale?: string; mapRoot?: string; module?: ModuleKind; noImplicitAny?: boolean; noLib?: boolean; noLibCheck?: boolean; noResolve?: boolean; out?: string; outDir?: string; removeComments?: boolean; sourceMap?: boolean; sourceRoot?: string; target?: ScriptTarget; version?: boolean; [option: string]: any; } export enum ModuleKind { None, CommonJS, AMD, } export enum ScriptTarget { ES3, ES5, } export interface ParsedCommandLine { options: CompilerOptions; filenames: string[]; errors: Diagnostic[]; } export interface CommandLineOption { name: string; type: any; error?: DiagnosticMessage; } export enum CharacterCodes { nullCharacter = 0, maxAsciiCharacter = 0x7F, lineFeed = 0x0A, // \n carriageReturn = 0x0D, // \r lineSeparator = 0x2028, paragraphSeparator = 0x2029, // REVIEW: do we need to support this? The scanner doesn't, but our IText does. This seems // like an odd disparity? (Or maybe it's completely fine for them to be different). nextLine = 0x0085, // Unicode 3.0 space characters space = 0x0020, // " " nonBreakingSpace = 0x00A0, // enQuad = 0x2000, emQuad = 0x2001, enSpace = 0x2002, emSpace = 0x2003, threePerEmSpace = 0x2004, fourPerEmSpace = 0x2005, sixPerEmSpace = 0x2006, figureSpace = 0x2007, punctuationSpace = 0x2008, thinSpace = 0x2009, hairSpace = 0x200A, zeroWidthSpace = 0x200B, narrowNoBreakSpace = 0x202F, ideographicSpace = 0x3000, mathematicalSpace = 0x205F, ogham = 0x1680, _ = 0x5F, $ = 0x24, _0 = 0x30, _1 = 0x31, _2 = 0x32, _3 = 0x33, _4 = 0x34, _5 = 0x35, _6 = 0x36, _7 = 0x37, _8 = 0x38, _9 = 0x39, a = 0x61, b = 0x62, c = 0x63, d = 0x64, e = 0x65, f = 0x66, g = 0x67, h = 0x68, i = 0x69, j = 0x6A, k = 0x6B, l = 0x6C, m = 0x6D, n = 0x6E, o = 0x6F, p = 0x70, q = 0x71, r = 0x72, s = 0x73, t = 0x74, u = 0x75, v = 0x76, w = 0x77, x = 0x78, y = 0x79, z = 0x7A, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4A, K = 0x4B, L = 0x4C, M = 0x4D, N = 0x4E, O = 0x4F, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5a, ampersand = 0x26, // & asterisk = 0x2A, // * at = 0x40, // @ backslash = 0x5C, // \ bar = 0x7C, // | caret = 0x5E, // ^ closeBrace = 0x7D, // } closeBracket = 0x5D, // ] closeParen = 0x29, // ) colon = 0x3A, // : comma = 0x2C, // , dot = 0x2E, // . doubleQuote = 0x22, // " equals = 0x3D, // = exclamation = 0x21, // ! greaterThan = 0x3E, // > lessThan = 0x3C, // < minus = 0x2D, // - openBrace = 0x7B, // { openBracket = 0x5B, // [ openParen = 0x28, // ( percent = 0x25, // % plus = 0x2B, // + question = 0x3F, // ? semicolon = 0x3B, // ; singleQuote = 0x27, // ' slash = 0x2F, // / tilde = 0x7E, // ~ backspace = 0x08, // \b formFeed = 0x0C, // \f byteOrderMark = 0xFEFF, tab = 0x09, // \t verticalTab = 0x0B, // \v } export interface CancellationToken { isCancellationRequested(): boolean; } export interface CompilerHost { getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; getDefaultLibFilename(): string; getCancellationToken? (): CancellationToken; writeFile(filename: string, data: string, onError?: (message: string) => void): void; getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; } }
src/compiler/types.ts
1
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.02301008068025112, 0.0006481903837993741, 0.00016121035150717944, 0.00016966793918982148, 0.002508669625967741 ]
{ "id": 3, "code_window": [ "\n", " var indent = 0;\n", " while (diagnosticChain) {\n", " if (indent) {\n", " messageText += sys.newLine;\n", " \n", " for (var i = 0; i < indent; i++) {\n", " messageText += \" \";\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " messageText += newLine;\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 224 }
// interfaces do not permit private members, these are errors interface I { private x: string; } interface I2<T> { private y: T; } var x: { private y: string; }
tests/cases/conformance/types/namedTypes/interfaceWithPrivateMember.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.0001688482443569228, 0.000167989288456738, 0.0001671303471084684, 0.000167989288456738, 8.58948624227196e-7 ]
{ "id": 3, "code_window": [ "\n", " var indent = 0;\n", " while (diagnosticChain) {\n", " if (indent) {\n", " messageText += sys.newLine;\n", " \n", " for (var i = 0; i < indent; i++) {\n", " messageText += \" \";\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " messageText += newLine;\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 224 }
class foo { }; function foo() {}
tests/cases/compiler/classOverloadForFunction.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017028771981131285, 0.00017028771981131285, 0.00017028771981131285, 0.00017028771981131285, 0 ]
{ "id": 3, "code_window": [ "\n", " var indent = 0;\n", " while (diagnosticChain) {\n", " if (indent) {\n", " messageText += sys.newLine;\n", " \n", " for (var i = 0; i < indent; i++) {\n", " messageText += \" \";\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " messageText += newLine;\n" ], "file_path": "src/compiler/core.ts", "type": "replace", "edit_start_line_idx": 224 }
declare var a1: number; declare class c1 { p1: number; } declare var instance1: c1; declare function f1(): c1;
tests/baselines/reference/project/outSingleFileSpecifyOutputFile/amd/bin/test.d.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.0001703988091321662, 0.0001703988091321662, 0.0001703988091321662, 0.0001703988091321662, 0 ]
{ "id": 10, "code_window": [ " getCurrentDirectory(): string;\n", " getCanonicalFileName(fileName: string): string;\n", " useCaseSensitiveFileNames(): boolean;\n", " }\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " getNewLine(): string;\n" ], "file_path": "src/compiler/types.ts", "type": "add", "edit_start_line_idx": 1000 }
/// <reference path="core.ts"/> /// <reference path="sys.ts"/> /// <reference path="types.ts"/> /// <reference path="scanner.ts"/> /// <reference path="parser.ts"/> /// <reference path="binder.ts"/> /// <reference path="checker.ts"/> /// <reference path="emitter.ts"/> /// <reference path="commandLineParser.ts"/> module ts { /// Checks to see if the locale is in the appropriate format, /// and if it is, attempt to set the appropriate language. function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean { var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp')); return false; } var language = matchResult[1]; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. if (!trySetLanguageAndTerritory(language, territory, errors) && !trySetLanguageAndTerritory(language, undefined, errors)) { errors.push(createCompilerDiagnostic(Diagnostics.Unsupported_locale_0, locale)); return false; } return true; } function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean { var compilerFilePath = sys.getExecutingFilePath(); var containingDirectoryPath = getDirectoryPath(compilerFilePath); var filePath = combinePaths(containingDirectoryPath, language); if (territory) { filePath = filePath + "-" + territory; } filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json")); if (!sys.fileExists(filePath)) { return false; } // TODO: Add codePage support for readFile? try { var fileContents = sys.readFile(filePath); } catch (e) { errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); return false; } try { localizedDiagnosticMessages = JSON.parse(fileContents); } catch (e) { errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath)); return false; } return true; } function countLines(program: Program): number { var count = 0; forEach(program.getSourceFiles(), file => { count += file.getLineAndCharacterFromPosition(file.end).line; }); return count; } function reportErrors(errors: Diagnostic[]) { for (var i = 0; i < errors.length; i++) { var error = errors[i]; if (error.file) { var loc = error.file.getLineAndCharacterFromPosition(error.start); sys.writeErr(error.file.filename + "(" + loc.line + "," + loc.character + "): " + error.messageText + sys.newLine); } else { sys.writeErr(error.messageText + sys.newLine); } } } function padLeft(s: string, length: number) { while (s.length < length) s = " " + s; return s; } function padRight(s: string, length: number) { while (s.length < length) s = s + " "; return s; } function reportDiagnostic(name: string, value: string) { sys.writeErr(padRight(name + ":", 12) + padLeft(value.toString(), 10) + sys.newLine); } function reportDiagnosticCount(name: string, count: number) { reportDiagnostic(name, "" + count); } function reportDiagnosticTime(name: string, time: number) { reportDiagnostic(name, (time / 1000).toFixed(2) + "s"); } function createCompilerHost(options: CompilerOptions): CompilerHost { var currentDirectory: string; var existingDirectories: Map<boolean> = {}; function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { try { var text = sys.readFile(filename, options.charset); } catch (e) { if (onError) onError(e.message); text = ""; } return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined; } function writeFile(fileName: string, data: string, onError?: (message: string) => void) { function directoryExists(directoryPath: string): boolean { if (hasProperty(existingDirectories, directoryPath)) { return true; } if (sys.directoryExists(directoryPath)) { existingDirectories[directoryPath] = true; return true; } return false; } function ensureDirectoriesExist(directoryPath: string) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); sys.createDirectory(directoryPath); } } try { ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data); } catch (e) { if (onError) onError(e.message); } } return { getSourceFile: getSourceFile, getDefaultLibFilename: () => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), "lib.d.ts"), writeFile: writeFile, getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, getCanonicalFileName: getCanonicalFileName }; } export function executeCommandLine(args: string[]): number { var cmds = parseCommandLine(args); if (cmds.filenames.length === 0 && !(cmds.options.help || cmds.options.version)) { cmds.errors.push(createCompilerDiagnostic(Diagnostics.No_input_files_specified)); } if (cmds.options.version) { } if (cmds.filenames.length === 0 || cmds.options.help) { // TODO (drosen): Usage. } // If a locale has been set but fails to load, act as if it was never specified, // but collect the errors to report along the way. if (cmds.options.locale) { validateLocaleAndSetLanguage(cmds.options.locale, cmds.errors); } if (cmds.errors.length) { reportErrors(cmds.errors); return 1; } var parseStart = new Date().getTime(); var program = createProgram(cmds.filenames, cmds.options, createCompilerHost(cmds.options)); var bindStart = new Date().getTime(); var errors = program.getDiagnostics(); if (errors.length) { var checkStart = bindStart; var emitStart = bindStart; var reportStart = bindStart; } else { var checker = program.getTypeChecker(); var checkStart = new Date().getTime(); var semanticErrors = checker.getDiagnostics(); var emitStart = new Date().getTime(); var emitErrors = checker.emitFiles().errors; var reportStart = new Date().getTime(); errors = concatenate(semanticErrors, emitErrors); } reportErrors(errors); if (cmds.options.diagnostics) { reportDiagnosticCount("Files", program.getSourceFiles().length); reportDiagnosticCount("Lines", countLines(program)); reportDiagnosticCount("Nodes", checker ? checker.getNodeCount() : 0); reportDiagnosticCount("Identifiers", checker ? checker.getIdentifierCount() : 0); reportDiagnosticCount("Symbols", checker ? checker.getSymbolCount() : 0); reportDiagnosticCount("Types", checker ? checker.getTypeCount() : 0); reportDiagnosticTime("Parse time", bindStart - parseStart); reportDiagnosticTime("Bind time", checkStart - bindStart); reportDiagnosticTime("Check time", emitStart - checkStart); reportDiagnosticTime("Emit time", reportStart - emitStart); reportDiagnosticTime("Total time", reportStart - parseStart); } return errors.length ? 1 : 0; } } sys.exit(ts.executeCommandLine(sys.args));
src/compiler/tc.ts
1
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.9968394041061401, 0.04184811934828758, 0.00016713447985239327, 0.00017577779362909496, 0.1991298794746399 ]
{ "id": 10, "code_window": [ " getCurrentDirectory(): string;\n", " getCanonicalFileName(fileName: string): string;\n", " useCaseSensitiveFileNames(): boolean;\n", " }\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " getNewLine(): string;\n" ], "file_path": "src/compiler/types.ts", "type": "add", "edit_start_line_idx": 1000 }
declare module WinJS { class Promise<T> { then<U>(success?: (value: T) => Promise<U>, error?: (error: any) => Promise<U>, progress?: (progress: any) => void): Promise<U>; } } declare module Data { export interface IListItem<T> { itemIndex: number; key: any; data: T; group: any; isHeader: boolean; cached: boolean; isNonSourceData: boolean; preventAugmentation: boolean; } export interface IVirtualList<T> { //removeIndices: WinJS.Promise<IListItem<T>[]>; removeIndices(indices: number[], options?: any): WinJS.Promise<IListItem<T>[]>; } export class VirtualList<T> implements IVirtualList<T> { //removeIndices: WinJS.Promise<IListItem<T>[]>; public removeIndices(indices: number[], options?: any): WinJS.Promise<IListItem<T>[]>; } }
tests/cases/compiler/arrayTypeInSignatureOfInterfaceAndClass.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017086805019062012, 0.00016962201334536076, 0.00016822681936901063, 0.00016977118502836674, 0.0000010834245358637418 ]
{ "id": 10, "code_window": [ " getCurrentDirectory(): string;\n", " getCanonicalFileName(fileName: string): string;\n", " useCaseSensitiveFileNames(): boolean;\n", " }\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " getNewLine(): string;\n" ], "file_path": "src/compiler/types.ts", "type": "add", "edit_start_line_idx": 1000 }
{ "scenario": "[Sourcemap]/[Sourceroot-RelativePath]: outputdir_module_multifolder: no outdir", "projectRoot": "tests/cases/projects/outputdir_module_multifolder", "inputFiles": [ "test.ts" ], "sourceMap": true, "sourceRoot": "../src", "declaration": true, "baselineCheck": true, "resolvedInputFiles": [ "test.ts", "ref/m1.ts", "../outputdir_module_multifolder_ref/m2.ts", "lib.d.ts" ], "emittedFiles": [ "ref/m1.js.map", "ref/m1.js", "ref/m1.d.ts", "../outputdir_module_multifolder_ref/m2.js.map", "../outputdir_module_multifolder_ref/m2.js", "../outputdir_module_multifolder_ref/m2.d.ts", "test.js.map", "test.js", "test.d.ts" ] }
tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/sourceRootRelativePathModuleMultifolderNoOutdir.json
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.00017402782395947725, 0.00017259817104786634, 0.00017102355195675045, 0.00017274310812354088, 0.000001230763928106171 ]
{ "id": 10, "code_window": [ " getCurrentDirectory(): string;\n", " getCanonicalFileName(fileName: string): string;\n", " useCaseSensitiveFileNames(): boolean;\n", " }\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " getNewLine(): string;\n" ], "file_path": "src/compiler/types.ts", "type": "add", "edit_start_line_idx": 1000 }
// -- operator on boolean type var BOOLEAN: boolean; function foo(): boolean { return true; } class A { public a: boolean; static foo() { return true; } } module M { export var n: boolean; } var objA = new A(); // boolean type var var ResultIsNumber1 = --BOOLEAN; var ResultIsNumber2 = BOOLEAN--; // boolean type literal var ResultIsNumber3 = --true; var ResultIsNumber4 = --{ x: true, y: false }; var ResultIsNumber5 = --{ x: true, y: (n: boolean) => { return n; } }; var ResultIsNumber6 = true--; var ResultIsNumber7 = { x: true, y: false }--; var ResultIsNumber8 = { x: true, y: (n: boolean) => { return n; } }--; // boolean type expressions var ResultIsNumber9 = --objA.a; var ResultIsNumber10 = --M.n; var ResultIsNumber11 = --foo(); var ResultIsNumber12 = --A.foo(); var ResultIsNumber13 = foo()--; var ResultIsNumber14 = A.foo()--; var ResultIsNumber15 = objA.a--; var ResultIsNumber16 = M.n--; // miss assignment operators --true; --BOOLEAN; --foo(); --objA.a; --M.n; --objA.a, M.n; true--; BOOLEAN--; foo()--; objA.a--; M.n--; objA.a--, M.n--;
tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts
0
https://github.com/microsoft/TypeScript/commit/2ed3de1c28ed201d7ddda80a54faa067bda37186
[ 0.0008968197507783771, 0.00029300161986611784, 0.00016754886019043624, 0.00017218492575921118, 0.0002700530458241701 ]
{ "id": 0, "code_window": [ " if not _is_bazel():\n", " metadata_files += [ctx.actions.declare_file(basename + ext) for ext in metadata]\n", "\n", " # We do this just when producing a flat module index for a publishable ng_module\n", " if is_legacy_ngc and _should_produce_flat_module_outs(ctx):\n", " flat_module_out = _flat_module_out_file(ctx)\n", " devmode_js_files.append(ctx.actions.declare_file(\"%s.js\" % flat_module_out))\n", " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if _should_produce_flat_module_outs(ctx):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 203 }
# 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 """Run Angular's AOT template compiler """ load( ":external.bzl", "COMMON_ATTRIBUTES", "COMMON_OUTPUTS", "DEFAULT_NG_COMPILER", "DEFAULT_NG_XI18N", "DEPS_ASPECTS", "NodeModuleInfo", "collect_node_modules_aspect", "compile_ts", "ts_providers_dict_to_struct", "tsc_wrapped_tsconfig", ) def compile_strategy(ctx): """Detect which strategy should be used to implement ng_module. Depending on the value of the 'compile' define flag, ng_module can be implemented in various ways. This function reads the configuration passed by the user and determines which mode is active. Args: ctx: skylark rule execution context Returns: one of 'legacy' or 'aot' depending on the configuration in ctx """ strategy = "legacy" if "compile" in ctx.var: strategy = ctx.var["compile"] if strategy not in ["legacy", "aot"]: fail("Unknown --define=compile value '%s'" % strategy) return strategy def _compiler_name(ctx): """Selects a user-visible name depending on the current compilation strategy. Args: ctx: skylark rule execution context Returns: the name of the current compiler to be displayed in build output """ strategy = compile_strategy(ctx) if strategy == "legacy": return "ngc" elif strategy == "aot": return "ngtsc" else: fail("unreachable") def _enable_ivy_value(ctx): """Determines the value of the enableIvy option in the generated tsconfig. Args: ctx: skylark rule execution context Returns: the value of enableIvy that needs to be set in angularCompilerOptions in the generated tsconfig """ strategy = compile_strategy(ctx) if strategy == "legacy": return False elif strategy == "aot": return "ngtsc" else: fail("unreachable") def _is_legacy_ngc(ctx): """Determines whether Angular outputs will be produced by the current compilation strategy. Args: ctx: skylark rule execution context Returns: true iff the current compilation strategy will produce View Engine compilation outputs (such as factory files), false otherwise """ strategy = compile_strategy(ctx) return strategy == "legacy" 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] # Return true if run with bazel (the open-sourced version of blaze), false if # run with blaze. def _is_bazel(): return not hasattr(native, "genmpm") def _flat_module_out_file(ctx): """Provide a default for the flat_module_out_file attribute. We cannot use the default="" parameter of ctx.attr because the value is calculated from other attributes (name) Args: ctx: skylark rule execution context Returns: a basename used for the flat module out (no extension) """ if hasattr(ctx.attr, "flat_module_out_file") and ctx.attr.flat_module_out_file: return ctx.attr.flat_module_out_file return "%s_public_index" % ctx.label.name def _should_produce_flat_module_outs(ctx): """Should we produce flat module outputs. We only produce flat module outs when we expect the ng_module is meant to be published, based on the presence of the module_name attribute. Args: ctx: skylark rule execution context Returns: true iff we should run the bundle_index_host to produce flat module metadata and bundle index """ return _is_bazel() and ctx.attr.module_name # 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): is_legacy_ngc = _is_legacy_ngc(ctx) devmode_js_files = [] closure_js_files = [] declaration_files = [] summary_files = [] metadata_files = [] factory_basename_set = depset([_basename_of(ctx, src) for src in ctx.files.factories]) for src in ctx.files.srcs + ctx.files.assets: package_prefix = ctx.label.package + "/" if ctx.label.package else "" # Strip external repository name from path if src is from external repository # If src is from external repository, it's short_path will be ../<external_repo_name>/... short_path = src.short_path if src.short_path[0:2] != ".." else "/".join(src.short_path.split("/")[2:]) if short_path.endswith(".ts") and not short_path.endswith(".d.ts"): basename = short_path[len(package_prefix):-len(".ts")] if (len(factory_basename_set.to_list()) == 0 or basename in factory_basename_set.to_list()): devmode_js = [ ".ngfactory.js", ".ngsummary.js", ".js", ] # Only ngc produces .json files, they're not needed in Ivy. if is_legacy_ngc: summaries = [".ngsummary.json"] metadata = [".metadata.json"] else: summaries = [] metadata = [] else: devmode_js = [".js"] if not _is_bazel(): devmode_js += [".ngfactory.js"] summaries = [] metadata = [] elif is_legacy_ngc and short_path.endswith(".css"): basename = short_path[len(package_prefix):-len(".css")] devmode_js = [ ".css.shim.ngstyle.js", ".css.ngstyle.js", ] summaries = [] metadata = [] 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.actions.declare_file(basename + ext) for ext in devmode_js] closure_js_files += [ctx.actions.declare_file(basename + ext) for ext in closure_js] declaration_files += [ctx.actions.declare_file(basename + ext) for ext in declarations] summary_files += [ctx.actions.declare_file(basename + ext) for ext in summaries] if not _is_bazel(): metadata_files += [ctx.actions.declare_file(basename + ext) for ext in metadata] # We do this just when producing a flat module index for a publishable ng_module if is_legacy_ngc and _should_produce_flat_module_outs(ctx): flat_module_out = _flat_module_out_file(ctx) devmode_js_files.append(ctx.actions.declare_file("%s.js" % flat_module_out)) closure_js_files.append(ctx.actions.declare_file("%s.closure.js" % flat_module_out)) bundle_index_typings = ctx.actions.declare_file("%s.d.ts" % flat_module_out) declaration_files.append(bundle_index_typings) metadata_files.append(ctx.actions.declare_file("%s.metadata.json" % flat_module_out)) else: bundle_index_typings = None # TODO(alxhub): i18n is only produced by the legacy compiler currently. This should be re-enabled # when ngtsc can extract messages if is_legacy_ngc: i18n_messages_files = [ctx.new_file(ctx.genfiles_dir, ctx.label.name + "_ngc_messages.xmb")] else: i18n_messages_files = [] return struct( closure_js = closure_js_files, devmode_js = devmode_js_files, declarations = declaration_files, summaries = summary_files, metadata = metadata_files, bundle_index_typings = bundle_index_typings, i18n_messages = i18n_messages_files, ) def _ngc_tsconfig(ctx, files, srcs, **kwargs): outs = _expected_outs(ctx) is_legacy_ngc = _is_legacy_ngc(ctx) if "devmode_manifest" in kwargs: expected_outs = outs.devmode_js + outs.declarations + outs.summaries + outs.metadata else: expected_outs = outs.closure_js angular_compiler_options = { "enableResourceInlining": ctx.attr.inline_resources, "generateCodeForLibraries": False, "allowEmptyCodegenFiles": True, # Summaries are only enabled if Angular outputs are to be produced. "enableSummariesForJit": is_legacy_ngc, "enableIvy": _enable_ivy_value(ctx), "fullTemplateTypeCheck": ctx.attr.type_check, # FIXME: wrong place to de-dupe "expectedOut": depset([o.path for o in expected_outs]).to_list(), } if _should_produce_flat_module_outs(ctx): angular_compiler_options["flatModuleId"] = ctx.attr.module_name angular_compiler_options["flatModuleOutFile"] = _flat_module_out_file(ctx) angular_compiler_options["flatModulePrivateSymbolPrefix"] = "_".join( [ctx.workspace_name] + ctx.label.package.split("/") + [ctx.label.name, ""], ) return dict(tsc_wrapped_tsconfig(ctx, files, srcs, **kwargs), **{ "angularCompilerOptions": angular_compiler_options, }) 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 and hasattr(ctx.rule.attr, "deps"): 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, node_opts, 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 node_opts: list of strings, extra nodejs options. 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. """ is_legacy_ngc = _is_legacy_ngc(ctx) mnemonic = "AngularTemplateCompile" progress_message = "Compiling Angular templates (%s) %s" % (_compiler_name(ctx), 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) + ["--node_options=%s" % opt for opt in node_opts]) # 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.actions.run( progress_message = progress_message, mnemonic = mnemonic, inputs = inputs, outputs = outputs, arguments = arguments, executable = ctx.executable.compiler, execution_requirements = { "supports-workers": supports_workers, }, ) if is_legacy_ngc and messages_out != None: ctx.actions.run( 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 explicitly # 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 _filter_ts_inputs(all_inputs): # 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. return [ f for f in all_inputs if f.path.endswith(".js") or f.path.endswith(".ts") or f.path.endswith(".json") ] def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts): # Give the Angular compiler all the user-listed assets file_inputs = list(ctx.files.assets) if hasattr(ctx.attr, "node_modules"): file_inputs.extend(_filter_ts_inputs(ctx.files.node_modules)) # 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) # Also include files from npm fine grained deps as action_inputs. # These deps are identified by the NodeModuleInfo provider. for d in ctx.attr.deps: if NodeModuleInfo in d: file_inputs.extend(_filter_ts_inputs(d.files)) # 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, node_opts) def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts) def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries + outs.metadata _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts) def _ts_expected_outs(ctx, label, srcs_files = []): # rules_typescript expects a function with two or more arguments, but our # implementation doesn't use the label(and **kwargs). _ignored = [label, srcs_files] return _expected_outs(ctx) 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 """ is_legacy_ngc = _is_legacy_ngc(ctx) providers = ts_compile_actions( ctx, is_library = True, # Filter out the node_modules from deps passed to TypeScript compiler # since they don't have the required providers. # They were added to the action inputs for tsc_wrapped already. # strict_deps checking currently skips node_modules. # TODO(alexeagle): turn on strict deps checking when we have a real # provider for JS/DTS inputs to ts_library. deps = [d for d in ctx.attr.deps if not NodeModuleInfo in d], compile_action = _prodmode_compile_action, devmode_compile_action = _devmode_compile_action, tsc_wrapped_tsconfig = _ngc_tsconfig, outputs = _ts_expected_outs, ) outs = _expected_outs(ctx) if is_legacy_ngc: providers["angular"] = { "summaries": outs.summaries, "metadata": outs.metadata, } providers["ngc_messages"] = outs.i18n_messages if is_legacy_ngc and _should_produce_flat_module_outs(ctx): if len(outs.metadata) > 1: fail("expecting exactly one metadata output for " + str(ctx.label)) providers["angular"]["flat_module_metadata"] = struct( module_name = ctx.attr.module_name, metadata_file = outs.metadata[0], typings_file = outs.bundle_index_typings, flat_module_out_file = _flat_module_out_file(ctx), ) return providers def _ng_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts)) local_deps_aspects = [collect_node_modules_aspect, _collect_summaries_aspect] # Workaround skydoc bug which assumes DEPS_ASPECTS is a str type [local_deps_aspects.append(a) for a in DEPS_ASPECTS] NG_MODULE_ATTRIBUTES = { "srcs": attr.label_list(allow_files = [".ts"]), # Note: DEPS_ASPECTS is already a list, we add the cast to workaround # https://github.com/bazelbuild/skydoc/issues/21 "deps": attr.label_list( doc = "Targets that are imported by this target", aspects = local_deps_aspects, ), "assets": attr.label_list( doc = ".html and .css files needed by the Angular compiler", 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), "inline_resources": attr.bool(default = True), "no_i18n": attr.bool(default = False), "compiler": attr.label( doc = """Sets a different ngc compiler binary to use for this library. The default ngc compiler depends on the `@npm//@angular/bazel` target which is setup for projects that use bazel managed npm deps that fetch the @angular/bazel npm package. It is recommended that you use the workspace name `@npm` for bazel managed deps so the default compiler works out of the box. Otherwise, you'll have to override the compiler attribute manually. """, default = Label(DEFAULT_NG_COMPILER), executable = True, cfg = "host", ), "ng_xi18n": attr.label( default = Label(DEFAULT_NG_XI18N), executable = True, cfg = "host", ), "_supports_workers": attr.bool(default = True), } NG_MODULE_RULE_ATTRS = dict(dict(COMMON_ATTRIBUTES, **NG_MODULE_ATTRIBUTES), **{ "tsconfig": attr.label(allow_files = True, single_file = True), "node_modules": attr.label( doc = """The npm packages which should be available during the compile. The default value of `@npm//typescript:typescript__typings` is for projects that use bazel managed npm deps. It is recommended that you use the workspace name `@npm` for bazel managed deps so the default value works out of the box. Otherwise, you'll have to override the node_modules attribute manually. This default is in place since code compiled by ng_module will always depend on at least the typescript default libs which are provided by `@npm//typescript:typescript__typings`. This attribute is DEPRECATED. As of version 0.18.0 the recommended approach to npm dependencies is to use fine grained npm dependencies which are setup with the `yarn_install` or `npm_install` rules. For example, in targets that used a `//:node_modules` filegroup, ``` ng_module( name = "my_lib", ... node_modules = "//:node_modules", ) ``` which specifies all files within the `//:node_modules` filegroup to be inputs to the `my_lib`. Using fine grained npm dependencies, `my_lib` is defined with only the npm dependencies that are needed: ``` ng_module( name = "my_lib", ... deps = [ "@npm//@types/foo", "@npm//@types/bar", "@npm//foo", "@npm//bar", ... ], ) ``` In this case, only the listed npm packages and their transitive deps are includes as inputs to the `my_lib` target which reduces the time required to setup the runfiles for this target (see https://github.com/bazelbuild/bazel/issues/5153). The default typescript libs are also available via the node_modules default in this case. The @npm external repository and the fine grained npm package targets are setup using the `yarn_install` or `npm_install` rule in your WORKSPACE file: yarn_install( name = "npm", package_json = "//:package.json", yarn_lock = "//:yarn.lock", ) """, default = Label("@npm//typescript:typescript__typings"), ), "entry_point": attr.string(), # Default is %{name}_public_index # The suffix points to the generated "bundle index" files that users import from # The default is intended to avoid collisions with the users input files. # Later packaging rules will point to these generated files as the entry point # into the package. # See the flatModuleOutFile documentation in # https://github.com/angular/angular/blob/master/packages/compiler-cli/src/transformers/api.ts "flat_module_out_file": attr.string(), }) ng_module = rule( implementation = _ng_module_impl, attrs = NG_MODULE_RULE_ATTRS, outputs = COMMON_OUTPUTS, ) """ Run the Angular AOT template compiler. This rule extends the [ts_library] rule. [ts_library]: http://tsetse.info/api/build_defs.html#ts_library """
packages/bazel/src/ng_module.bzl
1
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.9980295300483704, 0.0624505877494812, 0.00016402255278080702, 0.0003134501166641712, 0.22450602054595947 ]
{ "id": 0, "code_window": [ " if not _is_bazel():\n", " metadata_files += [ctx.actions.declare_file(basename + ext) for ext in metadata]\n", "\n", " # We do this just when producing a flat module index for a publishable ng_module\n", " if is_legacy_ngc and _should_produce_flat_module_outs(ctx):\n", " flat_module_out = _flat_module_out_file(ctx)\n", " devmode_js_files.append(ctx.actions.declare_file(\"%s.js\" % flat_module_out))\n", " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if _should_produce_flat_module_outs(ctx):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 203 }
/** * @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 {Subject} from 'rxjs'; export const patchDecodeBase64 = (proto: {decodeBase64: typeof atob}) => { let unpatch: () => void = () => undefined; if ((typeof atob === 'undefined') && (typeof Buffer === 'function')) { const oldDecodeBase64 = proto.decodeBase64; const newDecodeBase64 = (input: string) => Buffer.from(input, 'base64').toString('binary'); proto.decodeBase64 = newDecodeBase64; unpatch = () => { proto.decodeBase64 = oldDecodeBase64; }; } return unpatch; }; export class MockServiceWorkerContainer { private onControllerChange: Function[] = []; private onMessage: Function[] = []; mockRegistration: MockServiceWorkerRegistration|null = null; controller: MockServiceWorker|null = null; messages = new Subject(); notificationClicks = new Subject(); addEventListener(event: 'controllerchange'|'message', handler: Function) { if (event === 'controllerchange') { this.onControllerChange.push(handler); } else if (event === 'message') { this.onMessage.push(handler); } } removeEventListener(event: 'controllerchange', handler: Function) { if (event === 'controllerchange') { this.onControllerChange = this.onControllerChange.filter(h => h !== handler); } else if (event === 'message') { this.onMessage = this.onMessage.filter(h => h !== handler); } } async register(url: string): Promise<void> { return; } async getRegistration(): Promise<ServiceWorkerRegistration> { return this.mockRegistration as any; } setupSw(url: string = '/ngsw-worker.js'): void { this.mockRegistration = new MockServiceWorkerRegistration(); this.controller = new MockServiceWorker(this, url); this.onControllerChange.forEach(onChange => onChange(this.controller)); } sendMessage(value: Object): void { this.onMessage.forEach(onMessage => onMessage({ data: value, })); } } export class MockServiceWorker { constructor(private mock: MockServiceWorkerContainer, readonly scriptURL: string) {} postMessage(value: Object) { this.mock.messages.next(value); } } export class MockServiceWorkerRegistration { pushManager: PushManager = new MockPushManager() as any; } export class MockPushManager { private subscription: PushSubscription|null = null; getSubscription(): Promise<PushSubscription|null> { return Promise.resolve(this.subscription); } subscribe(options?: PushSubscriptionOptionsInit): Promise<PushSubscription> { this.subscription = new MockPushSubscription() as any; return Promise.resolve(this.subscription !); } } export class MockPushSubscription { unsubscribe(): Promise<boolean> { return Promise.resolve(true); } }
packages/service-worker/testing/mock.ts
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00023803710064385086, 0.00017375641618855298, 0.00016254658112302423, 0.00016618780500721186, 0.000021581778128165752 ]
{ "id": 0, "code_window": [ " if not _is_bazel():\n", " metadata_files += [ctx.actions.declare_file(basename + ext) for ext in metadata]\n", "\n", " # We do this just when producing a flat module index for a publishable ng_module\n", " if is_legacy_ngc and _should_produce_flat_module_outs(ctx):\n", " flat_module_out = _flat_module_out_file(ctx)\n", " devmode_js_files.append(ctx.actions.declare_file(\"%s.js\" % flat_module_out))\n", " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if _should_produce_flat_module_outs(ctx):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 203 }
var createTestPackage = require('../../helpers/test-package'); var Dgeni = require('dgeni'); describe('autoLinkCode post-processor', () => { let processor, autoLinkCode, aliasMap, filterPipes; beforeEach(() => { const testPackage = createTestPackage('angular-base-package'); const dgeni = new Dgeni([testPackage]); const injector = dgeni.configureInjector(); autoLinkCode = injector.get('autoLinkCode'); autoLinkCode.docTypes = ['class', 'pipe', 'function', 'const', 'member']; aliasMap = injector.get('aliasMap'); processor = injector.get('postProcessHtml'); processor.docTypes = ['test-doc']; processor.plugins = [autoLinkCode]; filterPipes = injector.get('filterPipes'); }); it('should insert an anchor into every code item that matches the id of an API doc', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code>MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code><a href="a/b/myclass" class="code-anchor">MyClass</a></code>'); }); it('should insert an anchor into every code item that matches an alias of an API doc', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass', 'foo.MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code>foo.MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code><a href="a/b/myclass" class="code-anchor">foo.MyClass</a></code>'); }); it('should match code items within a block of code that contain a dot in their identifier', () => { aliasMap.addDoc({ docType: 'member', id: 'MyEnum.Value', aliases: ['Value', 'MyEnum.Value'], path: 'a/b/myenum' }); const doc = { docType: 'test-doc', renderedContent: '<code>someFn(): MyEnum.Value</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code>someFn(): <a href="a/b/myenum" class="code-anchor">MyEnum.Value</a></code>'); }); it('should ignore code items that do not match a link to an API doc', () => { aliasMap.addDoc({ docType: 'guide', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code>MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code>MyClass</code>'); }); it('should ignore code items that are already inside a link', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<a href="..."><div><code>MyClass</code></div></a>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<a href="..."><div><code>MyClass</code></div></a>'); }); it('should ignore code items match an API doc but are not in the list of acceptable docTypes', () => { aliasMap.addDoc({ docType: 'directive', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code>MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code>MyClass</code>'); }); it('should ignore code items that match an API doc but are attached to other text via a dash', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code>xyz-MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code>xyz-MyClass</code>'); }); it('should ignore code items that are filtered out by custom filters', () => { autoLinkCode.customFilters = [filterPipes]; aliasMap.addDoc({ docType: 'pipe', id: 'MyClass', aliases: ['MyClass', 'myClass'], path: 'a/b/myclass', pipeOptions: { name: '\'myClass\'' } }); const doc = { docType: 'test-doc', renderedContent: '<code>{ xyz | myClass } { xyz|myClass } MyClass myClass OtherClass|MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code>' + '{ xyz | <a href="a/b/myclass" class="code-anchor">myClass</a> } ' + '{ xyz|<a href="a/b/myclass" class="code-anchor">myClass</a> } ' + '<a href="a/b/myclass" class="code-anchor">MyClass</a> ' + 'myClass OtherClass|<a href="a/b/myclass" class="code-anchor">MyClass</a>' + '</code>'); }); it('should ignore code items that match an internal API doc', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass', internal: true }); const doc = { docType: 'test-doc', renderedContent: '<code>MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code>MyClass</code>'); }); it('should insert anchors for individual text nodes within a code block', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code><span>MyClass</span><span>MyClass</span></code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code><span><a href="a/b/myclass" class="code-anchor">MyClass</a></span><span><a href="a/b/myclass" class="code-anchor">MyClass</a></span></code>'); }); it('should insert anchors for words that match within text nodes in a code block', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); aliasMap.addDoc({ docType: 'function', id: 'myFunc', aliases: ['myFunc'], path: 'ng/myfunc' }); aliasMap.addDoc({ docType: 'const', id: 'MY_CONST', aliases: ['MY_CONST'], path: 'ng/my_const' }); const doc = { docType: 'test-doc', renderedContent: '<code>myFunc() {\n return new MyClass(MY_CONST);\n}</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code><a href="ng/myfunc" class="code-anchor">myFunc</a>() {\n return new <a href="a/b/myclass" class="code-anchor">MyClass</a>(<a href="ng/my_const" class="code-anchor">MY_CONST</a>);\n}</code>'); }); it('should work with custom elements', () => { autoLinkCode.codeElements = ['code-example']; aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code-example>MyClass</code-example>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code-example><a href="a/b/myclass" class="code-anchor">MyClass</a></code-example>'); }); it('should ignore code blocks that are marked with a `no-auto-link` class', () => { aliasMap.addDoc({ docType: 'class', id: 'MyClass', aliases: ['MyClass'], path: 'a/b/myclass' }); const doc = { docType: 'test-doc', renderedContent: '<code class="no-auto-link">MyClass</code>' }; processor.$process([doc]); expect(doc.renderedContent).toEqual('<code class="no-auto-link">MyClass</code>'); }); });
aio/tools/transforms/angular-base-package/post-processors/auto-link-code.spec.js
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00017384556122124195, 0.0001703910529613495, 0.00016746181063354015, 0.00017076052608899772, 0.0000018449363778927363 ]
{ "id": 0, "code_window": [ " if not _is_bazel():\n", " metadata_files += [ctx.actions.declare_file(basename + ext) for ext in metadata]\n", "\n", " # We do this just when producing a flat module index for a publishable ng_module\n", " if is_legacy_ngc and _should_produce_flat_module_outs(ctx):\n", " flat_module_out = _flat_module_out_file(ctx)\n", " devmode_js_files.append(ctx.actions.declare_file(\"%s.js\" % flat_module_out))\n", " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if _should_produce_flat_module_outs(ctx):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 203 }
<!DOCTYPE html> <html lang="en"> <head> <base href="/"> <title>NgModule Minimal</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <app-root></app-root> </body> </html>
aio/content/examples/ngmodule-faq/src/index.1.html
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00017569765623193234, 0.0001704178430372849, 0.00016513802984263748, 0.0001704178430372849, 0.000005279813194647431 ]
{ "id": 1, "code_window": [ " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n", " else:\n", " bundle_index_typings = None\n", "\n", " # TODO(alxhub): i18n is only produced by the legacy compiler currently. This should be re-enabled\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if is_legacy_ngc:\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 209 }
/** * @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 {fixmeIvy, ivyEnabled, obsoleteInIvy} from '@angular/private/testing'; import * as path from 'path'; import * as shx from 'shelljs'; const corePackagePath = path.join(process.env['TEST_SRCDIR'] !, 'angular', 'packages', 'core', 'npm_package'); shx.cd(corePackagePath); /** * Utility functions that allows me to create fs paths * p`${foo}/some/${{bar}}/path` rather than path.join(foo, 'some', */ function p(templateStringArray: TemplateStringsArray) { const segments = []; for (const entry of templateStringArray) { segments.push(...entry.split('/').filter(s => s !== '')); } return path.join(...segments); } describe('@angular/core ng_package', () => { describe('misc root files', () => { describe('README.md', () => { it('should have a README.md file with basic info', () => { expect(shx.cat('README.md')).toContain(`Angular`); expect(shx.cat('README.md')).toContain(`https://github.com/angular/angular`); }); }); }); describe('primary entry-point', () => { describe('package.json', () => { const packageJson = 'package.json'; it('should have a package.json file', () => { expect(shx.grep('"name":', packageJson)).toContain(`@angular/core`); }); it('should contain correct version number with the PLACEHOLDER string replaced', () => { expect(shx.grep('"version":', packageJson)).toMatch(/\d+\.\d+\.\d+(?!-PLACEHOLDER)/); }); it('should contain module resolution mappings', () => { expect(shx.grep('"main":', packageJson)).toContain(`./bundles/core.umd.js`); expect(shx.grep('"module":', packageJson)).toContain(`./fesm5/core.js`); expect(shx.grep('"es2015":', packageJson)).toContain(`./fesm2015/core.js`); expect(shx.grep('"esm5":', packageJson)).toContain(`./esm5/core.js`); expect(shx.grep('"esm2015":', packageJson)).toContain(`./esm2015/core.js`); expect(shx.grep('"typings":', packageJson)).toContain(`./core.d.ts`); }); it('should contain metadata for ng update', () => { expect(shx.cat(packageJson)).not.toContain('NG_UPDATE_PACKAGE_GROUP'); expect(JSON.parse(shx.cat(packageJson))['ng-update']['packageGroup']) .toContain('@angular/core'); }); }); describe('typescript support', () => { fixmeIvy('FW-738: ngtsc doesn\'t generate flat index files') .it('should have an index d.ts file', () => { expect(shx.cat('core.d.ts')).toContain(`export *`); }); it('should not have amd module names', () => { expect(shx.cat('public_api.d.ts')).not.toContain('<amd-module name'); }); }); describe('closure', () => { it('should contain externs', () => { expect(shx.cat('src/testability/testability.externs.js')).toContain('/** @externs */'); }); }); obsoleteInIvy('metadata files are no longer needed or produced in Ivy') .describe('angular metadata', () => { it('should have metadata.json files', () => { expect(shx.cat('core.metadata.json')).toContain(`"__symbolic":"module"`); }); }); describe('fesm2015', () => { it('should have a fesm15 file in the /fesm2015 directory', () => { expect(shx.cat('fesm2015/core.js')).toContain(`export {`); }); it('should have a source map', () => { expect(shx.cat('fesm2015/core.js.map')) .toContain(`{"version":3,"file":"core.js","sources":`); }); it('should have the version info in the header', () => { expect(shx.cat('fesm2015/core.js')) .toMatch(/@license Angular v\d+\.\d+\.\d+(?!-PLACEHOLDER)/); }); obsoleteInIvy('we no longer need to export private symbols') .it('should have been built from the generated bundle index', () => { expect(shx.cat('fesm2015/core.js')).toMatch('export {.*makeParamDecorator'); }); }); describe('fesm5', () => { it('should have a fesm5 file in the /fesm5 directory', () => { expect(shx.cat('fesm5/core.js')).toContain(`export {`); }); it('should have a source map', () => { expect(shx.cat('fesm5/core.js.map')).toContain(`{"version":3,"file":"core.js","sources":`); }); it('should not be processed by tsickle', () => { expect(shx.cat('fesm5/core.js')).not.toContain('@fileoverview added by tsickle'); }); if (ivyEnabled) { it('should have decorators downleveled to static props e.g. ngInjectableDef', () => { expect(shx.cat('fesm5/core.js')).not.toContain('__decorate'); expect(shx.cat('fesm5/core.js')).toContain('.ngInjectableDef = '); }); } else { it('should have decorators', () => { expect(shx.cat('fesm5/core.js')).toContain('__decorate'); }); } it('should load tslib from external bundle', () => { expect(shx.cat('fesm5/core.js')).not.toContain('function __extends'); expect(shx.cat('fesm5/core.js')).toMatch('import {.*__extends'); }); obsoleteInIvy('we no longer need to export private symbols') .it('should have been built from the generated bundle index', () => { expect(shx.cat('fesm5/core.js')).toMatch('export {.*makeParamDecorator'); }); }); describe('esm2015', () => { it('should not contain any *.ngfactory.js files', () => { expect(shx.find('esm2015').filter(f => f.endsWith('.ngfactory.js'))).toEqual([]); }); it('should not contain any *.ngsummary.js files', () => { expect(shx.find('esm2015').filter(f => f.endsWith('.ngsummary.js'))).toEqual([]); }); }); describe('esm5', () => { it('should not contain any *.ngfactory.js files', () => { expect(shx.find('esm5').filter(f => f.endsWith('.ngfactory.js'))).toEqual([]); }); it('should not contain any *.ngsummary.js files', () => { expect(shx.find('esm5').filter(f => f.endsWith('.ngsummary.js'))).toEqual([]); }); }); describe('umd', () => { it('should have a umd file in the /bundles directory', () => { expect(shx.ls('bundles/core.umd.js').length).toBe(1, 'File not found'); }); it('should have a source map next to the umd file', () => { expect(shx.ls('bundles/core.umd.js.map').length).toBe(1, 'File not found'); }); it('should have a minified umd file in the /bundles directory', () => { expect(shx.ls('bundles/core.umd.min.js').length).toBe(1, 'File not found'); }); it('should have a source map next to the minified umd file', () => { expect(shx.ls('bundles/core.umd.min.js.map').length).toBe(1, 'File not found'); }); it('should have the version info in the header', () => { expect(shx.cat('bundles/core.umd.js')) .toMatch(/@license Angular v\d+\.\d+\.\d+(?!-PLACEHOLDER)/); }); it('should have tslib helpers', () => { expect(shx.cat('bundles/core.umd.js')).toContain('function __extends'); expect(shx.cat('bundles/core.umd.js')).not.toContain('undefined.__extends'); }); it('should have an AMD name', () => { expect(shx.cat('bundles/core.umd.js')).toContain('define(\'@angular/core\''); }); it('should define ng global symbols', () => { expect(shx.cat('bundles/core.umd.js')).toContain('global.ng.core = {}'); }); }); }); describe('secondary entry-point', () => { describe('package.json', () => { const packageJson = p `testing/package.json`; it('should have a package.json file', () => { expect(shx.grep('"name":', packageJson)).toContain(`@angular/core/testing`); }); it('should have its module resolution mappings defined in the nested package.json', () => { const packageJson = p `testing/package.json`; expect(shx.grep('"main":', packageJson)).toContain(`../bundles/core-testing.umd.js`); expect(shx.grep('"module":', packageJson)).toContain(`../fesm5/testing.js`); expect(shx.grep('"es2015":', packageJson)).toContain(`../fesm2015/testing.js`); expect(shx.grep('"esm5":', packageJson)).toContain(`../esm5/testing/testing.js`); expect(shx.grep('"esm2015":', packageJson)).toContain(`../esm2015/testing/testing.js`); expect(shx.grep('"typings":', packageJson)).toContain(`./testing.d.ts`); }); }); describe('typings', () => { const typingsFile = p `testing/index.d.ts`; it('should have a typings file', () => { expect(shx.cat(typingsFile)).toContain('export * from \'./public_api\';'); }); obsoleteInIvy( 'now that we don\'t need metadata files, we don\'t need these redirects to help resolve paths to them') .it('should have an \'redirect\' d.ts file in the parent dir', () => { expect(shx.cat('testing.d.ts')).toContain(`export *`); }); }); obsoleteInIvy('metadata files are no longer needed or produced in Ivy') .describe('angular metadata file', () => { it('should have a \'redirect\' metadata.json file next to the d.ts file', () => { expect(shx.cat('testing.metadata.json')) .toContain( `"exports":[{"from":"./testing/testing"}],"flatModuleIndexRedirect":true`); }); }); describe('fesm2015', () => { it('should have a fesm15 file in the /fesm2015 directory', () => { expect(shx.cat('fesm2015/testing.js')).toContain(`export {`); }); it('should have a source map', () => { expect(shx.cat('fesm2015/testing.js.map')) .toContain(`{"version":3,"file":"testing.js","sources":`); }); it('should have the version info in the header', () => { expect(shx.cat('fesm2015/testing.js')) .toMatch(/@license Angular v\d+\.\d+\.\d+(?!-PLACEHOLDER)/); }); }); describe('fesm5', () => { it('should have a fesm5 file in the /fesm5 directory', () => { expect(shx.cat('fesm5/testing.js')).toContain(`export {`); }); it('should have a source map', () => { expect(shx.cat('fesm5/testing.js.map')) .toContain(`{"version":3,"file":"testing.js","sources":`); }); }); describe('umd', () => { it('should have a umd file in the /bundles directory', () => { expect(shx.ls('bundles/core-testing.umd.js').length).toBe(1, 'File not found'); }); it('should have a source map next to the umd file', () => { expect(shx.ls('bundles/core-testing.umd.js.map').length).toBe(1, 'File not found'); }); it('should have a minified umd file in the /bundles directory', () => { expect(shx.ls('bundles/core-testing.umd.min.js').length).toBe(1, 'File not found'); }); it('should have a source map next to the minified umd file', () => { expect(shx.ls('bundles/core-testing.umd.min.js.map').length).toBe(1, 'File not found'); }); it('should have an AMD name', () => { expect(shx.cat('bundles/core-testing.umd.js')) .toContain('define(\'@angular/core/testing\''); }); it('should define ng global symbols', () => { expect(shx.cat('bundles/core-testing.umd.js')).toContain('global.ng.core.testing = {}'); }); }); }); });
packages/bazel/test/ng_package/core_package.spec.ts
1
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00018205509695690125, 0.00017233843391295522, 0.00016682464047335088, 0.00017253425903618336, 0.0000030135597626212984 ]
{ "id": 1, "code_window": [ " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n", " else:\n", " bundle_index_typings = None\n", "\n", " # TODO(alxhub): i18n is only produced by the legacy compiler currently. This should be re-enabled\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if is_legacy_ngc:\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 209 }
set -e export NVM_DIR="/Users/Shared/jenkins/nvm" . "$NVM_DIR/nvm.sh" # This loads nvm export ANDROID_SDK="/Users/Shared/jenkins/android-sdk" export PATH+=":$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools" export PATH+=":/usr/local/git/bin" export DART_CHANNEL=dev export ARCH=macos-ia32 export PERF_BROWSERS=ChromeAndroid export CLOUD_SECRET_PATH="/Users/Shared/jenkins/keys/perf-cloud-secret" export GIT_SHA=$(git rev-parse HEAD) nvm use 0.10 ./scripts/ci/init_android.sh ./scripts/ci/install_dart.sh ${DART_CHANNEL} ${ARCH} npm cache clean # use newest npm because of errors during npm install like # npm ERR! EEXIST, open '/Users/Shared/Jenkins/.npm/e4d0eb16-adable-stream-1-1-13-package-tgz.lock' npm install -g [email protected] npm install ./scripts/ci/build_js.sh ./scripts/ci/build_dart.sh ./scripts/ci/test_perf.sh
scripts/jenkins/jenkins_perf.sh
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00016717272228561342, 0.0001666676689637825, 0.00016619512462057173, 0.00016663513088133186, 3.997648150289024e-7 ]
{ "id": 1, "code_window": [ " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n", " else:\n", " bundle_index_typings = None\n", "\n", " # TODO(alxhub): i18n is only produced by the legacy compiler currently. This should be re-enabled\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if is_legacy_ngc:\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 209 }
.blue { color: blue }
packages/compiler-cli/integrationtest/src/shared.css
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.0001680406858213246, 0.0001680406858213246, 0.0001680406858213246, 0.0001680406858213246, 0 ]
{ "id": 1, "code_window": [ " closure_js_files.append(ctx.actions.declare_file(\"%s.closure.js\" % flat_module_out))\n", " bundle_index_typings = ctx.actions.declare_file(\"%s.d.ts\" % flat_module_out)\n", " declaration_files.append(bundle_index_typings)\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n", " else:\n", " bundle_index_typings = None\n", "\n", " # TODO(alxhub): i18n is only produced by the legacy compiler currently. This should be re-enabled\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if is_legacy_ngc:\n", " metadata_files.append(ctx.actions.declare_file(\"%s.metadata.json\" % flat_module_out))\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 209 }
const {resolve} = require('canonical-path'); const Package = require('dgeni').Package; const basePackage = require('../angular-base-package'); const contentPackage = require('../content-package'); const {CONTENTS_PATH, TEMPLATES_PATH, requireFolder} = require('../config'); const CLI_SOURCE_ROOT = resolve(CONTENTS_PATH, 'cli-src'); const CLI_SOURCE_PATH = resolve(CLI_SOURCE_ROOT, 'node_modules/@angular/cli'); const CLI_SOURCE_HELP_PATH = resolve(CLI_SOURCE_PATH, 'help'); // Define the dgeni package for generating the docs module.exports = new Package('cli-docs', [basePackage, contentPackage]) // Register the services and file readers .factory(require('./readers/cli-command')) // Register the processors .processor(require('./processors/processCliContainerDoc')) .processor(require('./processors/processCliCommands')) .processor(require('./processors/filterHiddenCommands')) // Configure file reading .config(function(readFilesProcessor, cliCommandFileReader) { readFilesProcessor.fileReaders.push(cliCommandFileReader); readFilesProcessor.sourceFiles = readFilesProcessor.sourceFiles.concat([ { basePath: CLI_SOURCE_HELP_PATH, include: resolve(CLI_SOURCE_HELP_PATH, '*.json'), fileReader: 'cliCommandFileReader' }, { basePath: CONTENTS_PATH, include: resolve(CONTENTS_PATH, 'cli/**'), fileReader: 'contentFileReader' }, ]); }) .config(function(templateFinder, templateEngine, getInjectables) { // Where to find the templates for the CLI doc rendering templateFinder.templateFolders.unshift(resolve(TEMPLATES_PATH, 'cli')); // Add in templating filters and tags templateEngine.filters = templateEngine.filters.concat(getInjectables(requireFolder(__dirname, './rendering'))); }) .config(function(renderDocsProcessor) { const cliPackage = require(resolve(CLI_SOURCE_PATH, 'package.json')); const repoUrlParts = cliPackage.repository.url.replace(/\.git$/, '').split('/'); const version = `v${cliPackage.version}`; const repo = repoUrlParts.pop(); const owner = repoUrlParts.pop(); const cliVersionInfo = { gitRepoInfo: { owner, repo }, currentVersion: { raw: version } }; // Add the cli version data to the renderer, for use in things like github links renderDocsProcessor.extraData.cliVersionInfo = cliVersionInfo; }) .config(function(convertToJsonProcessor, postProcessHtml) { convertToJsonProcessor.docTypes = convertToJsonProcessor.docTypes.concat(['cli-command', 'cli-overview']); postProcessHtml.docTypes = postProcessHtml.docTypes.concat(['cli-command', 'cli-overview']); });
aio/tools/transforms/cli-docs-package/index.js
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00017298688180744648, 0.00016922279610298574, 0.000166525220265612, 0.00016920926282182336, 0.0000018726763073573238 ]
{ "id": 2, "code_window": [ " });\n", "\n", "\n", " describe('typescript support', () => {\n", "\n", " fixmeIvy('FW-738: ngtsc doesn\\'t generate flat index files')\n", " .it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n", "\n", " it('should not have amd module names',\n", " () => { expect(shx.cat('public_api.d.ts')).not.toContain('<amd-module name'); });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n" ], "file_path": "packages/bazel/test/ng_package/core_package.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
# 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 """Run Angular's AOT template compiler """ load( ":external.bzl", "COMMON_ATTRIBUTES", "COMMON_OUTPUTS", "DEFAULT_NG_COMPILER", "DEFAULT_NG_XI18N", "DEPS_ASPECTS", "NodeModuleInfo", "collect_node_modules_aspect", "compile_ts", "ts_providers_dict_to_struct", "tsc_wrapped_tsconfig", ) def compile_strategy(ctx): """Detect which strategy should be used to implement ng_module. Depending on the value of the 'compile' define flag, ng_module can be implemented in various ways. This function reads the configuration passed by the user and determines which mode is active. Args: ctx: skylark rule execution context Returns: one of 'legacy' or 'aot' depending on the configuration in ctx """ strategy = "legacy" if "compile" in ctx.var: strategy = ctx.var["compile"] if strategy not in ["legacy", "aot"]: fail("Unknown --define=compile value '%s'" % strategy) return strategy def _compiler_name(ctx): """Selects a user-visible name depending on the current compilation strategy. Args: ctx: skylark rule execution context Returns: the name of the current compiler to be displayed in build output """ strategy = compile_strategy(ctx) if strategy == "legacy": return "ngc" elif strategy == "aot": return "ngtsc" else: fail("unreachable") def _enable_ivy_value(ctx): """Determines the value of the enableIvy option in the generated tsconfig. Args: ctx: skylark rule execution context Returns: the value of enableIvy that needs to be set in angularCompilerOptions in the generated tsconfig """ strategy = compile_strategy(ctx) if strategy == "legacy": return False elif strategy == "aot": return "ngtsc" else: fail("unreachable") def _is_legacy_ngc(ctx): """Determines whether Angular outputs will be produced by the current compilation strategy. Args: ctx: skylark rule execution context Returns: true iff the current compilation strategy will produce View Engine compilation outputs (such as factory files), false otherwise """ strategy = compile_strategy(ctx) return strategy == "legacy" 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] # Return true if run with bazel (the open-sourced version of blaze), false if # run with blaze. def _is_bazel(): return not hasattr(native, "genmpm") def _flat_module_out_file(ctx): """Provide a default for the flat_module_out_file attribute. We cannot use the default="" parameter of ctx.attr because the value is calculated from other attributes (name) Args: ctx: skylark rule execution context Returns: a basename used for the flat module out (no extension) """ if hasattr(ctx.attr, "flat_module_out_file") and ctx.attr.flat_module_out_file: return ctx.attr.flat_module_out_file return "%s_public_index" % ctx.label.name def _should_produce_flat_module_outs(ctx): """Should we produce flat module outputs. We only produce flat module outs when we expect the ng_module is meant to be published, based on the presence of the module_name attribute. Args: ctx: skylark rule execution context Returns: true iff we should run the bundle_index_host to produce flat module metadata and bundle index """ return _is_bazel() and ctx.attr.module_name # 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): is_legacy_ngc = _is_legacy_ngc(ctx) devmode_js_files = [] closure_js_files = [] declaration_files = [] summary_files = [] metadata_files = [] factory_basename_set = depset([_basename_of(ctx, src) for src in ctx.files.factories]) for src in ctx.files.srcs + ctx.files.assets: package_prefix = ctx.label.package + "/" if ctx.label.package else "" # Strip external repository name from path if src is from external repository # If src is from external repository, it's short_path will be ../<external_repo_name>/... short_path = src.short_path if src.short_path[0:2] != ".." else "/".join(src.short_path.split("/")[2:]) if short_path.endswith(".ts") and not short_path.endswith(".d.ts"): basename = short_path[len(package_prefix):-len(".ts")] if (len(factory_basename_set.to_list()) == 0 or basename in factory_basename_set.to_list()): devmode_js = [ ".ngfactory.js", ".ngsummary.js", ".js", ] # Only ngc produces .json files, they're not needed in Ivy. if is_legacy_ngc: summaries = [".ngsummary.json"] metadata = [".metadata.json"] else: summaries = [] metadata = [] else: devmode_js = [".js"] if not _is_bazel(): devmode_js += [".ngfactory.js"] summaries = [] metadata = [] elif is_legacy_ngc and short_path.endswith(".css"): basename = short_path[len(package_prefix):-len(".css")] devmode_js = [ ".css.shim.ngstyle.js", ".css.ngstyle.js", ] summaries = [] metadata = [] 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.actions.declare_file(basename + ext) for ext in devmode_js] closure_js_files += [ctx.actions.declare_file(basename + ext) for ext in closure_js] declaration_files += [ctx.actions.declare_file(basename + ext) for ext in declarations] summary_files += [ctx.actions.declare_file(basename + ext) for ext in summaries] if not _is_bazel(): metadata_files += [ctx.actions.declare_file(basename + ext) for ext in metadata] # We do this just when producing a flat module index for a publishable ng_module if is_legacy_ngc and _should_produce_flat_module_outs(ctx): flat_module_out = _flat_module_out_file(ctx) devmode_js_files.append(ctx.actions.declare_file("%s.js" % flat_module_out)) closure_js_files.append(ctx.actions.declare_file("%s.closure.js" % flat_module_out)) bundle_index_typings = ctx.actions.declare_file("%s.d.ts" % flat_module_out) declaration_files.append(bundle_index_typings) metadata_files.append(ctx.actions.declare_file("%s.metadata.json" % flat_module_out)) else: bundle_index_typings = None # TODO(alxhub): i18n is only produced by the legacy compiler currently. This should be re-enabled # when ngtsc can extract messages if is_legacy_ngc: i18n_messages_files = [ctx.new_file(ctx.genfiles_dir, ctx.label.name + "_ngc_messages.xmb")] else: i18n_messages_files = [] return struct( closure_js = closure_js_files, devmode_js = devmode_js_files, declarations = declaration_files, summaries = summary_files, metadata = metadata_files, bundle_index_typings = bundle_index_typings, i18n_messages = i18n_messages_files, ) def _ngc_tsconfig(ctx, files, srcs, **kwargs): outs = _expected_outs(ctx) is_legacy_ngc = _is_legacy_ngc(ctx) if "devmode_manifest" in kwargs: expected_outs = outs.devmode_js + outs.declarations + outs.summaries + outs.metadata else: expected_outs = outs.closure_js angular_compiler_options = { "enableResourceInlining": ctx.attr.inline_resources, "generateCodeForLibraries": False, "allowEmptyCodegenFiles": True, # Summaries are only enabled if Angular outputs are to be produced. "enableSummariesForJit": is_legacy_ngc, "enableIvy": _enable_ivy_value(ctx), "fullTemplateTypeCheck": ctx.attr.type_check, # FIXME: wrong place to de-dupe "expectedOut": depset([o.path for o in expected_outs]).to_list(), } if _should_produce_flat_module_outs(ctx): angular_compiler_options["flatModuleId"] = ctx.attr.module_name angular_compiler_options["flatModuleOutFile"] = _flat_module_out_file(ctx) angular_compiler_options["flatModulePrivateSymbolPrefix"] = "_".join( [ctx.workspace_name] + ctx.label.package.split("/") + [ctx.label.name, ""], ) return dict(tsc_wrapped_tsconfig(ctx, files, srcs, **kwargs), **{ "angularCompilerOptions": angular_compiler_options, }) 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 and hasattr(ctx.rule.attr, "deps"): 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, node_opts, 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 node_opts: list of strings, extra nodejs options. 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. """ is_legacy_ngc = _is_legacy_ngc(ctx) mnemonic = "AngularTemplateCompile" progress_message = "Compiling Angular templates (%s) %s" % (_compiler_name(ctx), 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) + ["--node_options=%s" % opt for opt in node_opts]) # 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.actions.run( progress_message = progress_message, mnemonic = mnemonic, inputs = inputs, outputs = outputs, arguments = arguments, executable = ctx.executable.compiler, execution_requirements = { "supports-workers": supports_workers, }, ) if is_legacy_ngc and messages_out != None: ctx.actions.run( 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 explicitly # 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 _filter_ts_inputs(all_inputs): # 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. return [ f for f in all_inputs if f.path.endswith(".js") or f.path.endswith(".ts") or f.path.endswith(".json") ] def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts): # Give the Angular compiler all the user-listed assets file_inputs = list(ctx.files.assets) if hasattr(ctx.attr, "node_modules"): file_inputs.extend(_filter_ts_inputs(ctx.files.node_modules)) # 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) # Also include files from npm fine grained deps as action_inputs. # These deps are identified by the NodeModuleInfo provider. for d in ctx.attr.deps: if NodeModuleInfo in d: file_inputs.extend(_filter_ts_inputs(d.files)) # 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, node_opts) def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts) def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries + outs.metadata _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts) def _ts_expected_outs(ctx, label, srcs_files = []): # rules_typescript expects a function with two or more arguments, but our # implementation doesn't use the label(and **kwargs). _ignored = [label, srcs_files] return _expected_outs(ctx) 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 """ is_legacy_ngc = _is_legacy_ngc(ctx) providers = ts_compile_actions( ctx, is_library = True, # Filter out the node_modules from deps passed to TypeScript compiler # since they don't have the required providers. # They were added to the action inputs for tsc_wrapped already. # strict_deps checking currently skips node_modules. # TODO(alexeagle): turn on strict deps checking when we have a real # provider for JS/DTS inputs to ts_library. deps = [d for d in ctx.attr.deps if not NodeModuleInfo in d], compile_action = _prodmode_compile_action, devmode_compile_action = _devmode_compile_action, tsc_wrapped_tsconfig = _ngc_tsconfig, outputs = _ts_expected_outs, ) outs = _expected_outs(ctx) if is_legacy_ngc: providers["angular"] = { "summaries": outs.summaries, "metadata": outs.metadata, } providers["ngc_messages"] = outs.i18n_messages if is_legacy_ngc and _should_produce_flat_module_outs(ctx): if len(outs.metadata) > 1: fail("expecting exactly one metadata output for " + str(ctx.label)) providers["angular"]["flat_module_metadata"] = struct( module_name = ctx.attr.module_name, metadata_file = outs.metadata[0], typings_file = outs.bundle_index_typings, flat_module_out_file = _flat_module_out_file(ctx), ) return providers def _ng_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts)) local_deps_aspects = [collect_node_modules_aspect, _collect_summaries_aspect] # Workaround skydoc bug which assumes DEPS_ASPECTS is a str type [local_deps_aspects.append(a) for a in DEPS_ASPECTS] NG_MODULE_ATTRIBUTES = { "srcs": attr.label_list(allow_files = [".ts"]), # Note: DEPS_ASPECTS is already a list, we add the cast to workaround # https://github.com/bazelbuild/skydoc/issues/21 "deps": attr.label_list( doc = "Targets that are imported by this target", aspects = local_deps_aspects, ), "assets": attr.label_list( doc = ".html and .css files needed by the Angular compiler", 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), "inline_resources": attr.bool(default = True), "no_i18n": attr.bool(default = False), "compiler": attr.label( doc = """Sets a different ngc compiler binary to use for this library. The default ngc compiler depends on the `@npm//@angular/bazel` target which is setup for projects that use bazel managed npm deps that fetch the @angular/bazel npm package. It is recommended that you use the workspace name `@npm` for bazel managed deps so the default compiler works out of the box. Otherwise, you'll have to override the compiler attribute manually. """, default = Label(DEFAULT_NG_COMPILER), executable = True, cfg = "host", ), "ng_xi18n": attr.label( default = Label(DEFAULT_NG_XI18N), executable = True, cfg = "host", ), "_supports_workers": attr.bool(default = True), } NG_MODULE_RULE_ATTRS = dict(dict(COMMON_ATTRIBUTES, **NG_MODULE_ATTRIBUTES), **{ "tsconfig": attr.label(allow_files = True, single_file = True), "node_modules": attr.label( doc = """The npm packages which should be available during the compile. The default value of `@npm//typescript:typescript__typings` is for projects that use bazel managed npm deps. It is recommended that you use the workspace name `@npm` for bazel managed deps so the default value works out of the box. Otherwise, you'll have to override the node_modules attribute manually. This default is in place since code compiled by ng_module will always depend on at least the typescript default libs which are provided by `@npm//typescript:typescript__typings`. This attribute is DEPRECATED. As of version 0.18.0 the recommended approach to npm dependencies is to use fine grained npm dependencies which are setup with the `yarn_install` or `npm_install` rules. For example, in targets that used a `//:node_modules` filegroup, ``` ng_module( name = "my_lib", ... node_modules = "//:node_modules", ) ``` which specifies all files within the `//:node_modules` filegroup to be inputs to the `my_lib`. Using fine grained npm dependencies, `my_lib` is defined with only the npm dependencies that are needed: ``` ng_module( name = "my_lib", ... deps = [ "@npm//@types/foo", "@npm//@types/bar", "@npm//foo", "@npm//bar", ... ], ) ``` In this case, only the listed npm packages and their transitive deps are includes as inputs to the `my_lib` target which reduces the time required to setup the runfiles for this target (see https://github.com/bazelbuild/bazel/issues/5153). The default typescript libs are also available via the node_modules default in this case. The @npm external repository and the fine grained npm package targets are setup using the `yarn_install` or `npm_install` rule in your WORKSPACE file: yarn_install( name = "npm", package_json = "//:package.json", yarn_lock = "//:yarn.lock", ) """, default = Label("@npm//typescript:typescript__typings"), ), "entry_point": attr.string(), # Default is %{name}_public_index # The suffix points to the generated "bundle index" files that users import from # The default is intended to avoid collisions with the users input files. # Later packaging rules will point to these generated files as the entry point # into the package. # See the flatModuleOutFile documentation in # https://github.com/angular/angular/blob/master/packages/compiler-cli/src/transformers/api.ts "flat_module_out_file": attr.string(), }) ng_module = rule( implementation = _ng_module_impl, attrs = NG_MODULE_RULE_ATTRS, outputs = COMMON_OUTPUTS, ) """ Run the Angular AOT template compiler. This rule extends the [ts_library] rule. [ts_library]: http://tsetse.info/api/build_defs.html#ts_library """
packages/bazel/src/ng_module.bzl
1
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.0046533518470823765, 0.00039819872472435236, 0.00016272181528620422, 0.00017081348050851375, 0.0007024391670711339 ]
{ "id": 2, "code_window": [ " });\n", "\n", "\n", " describe('typescript support', () => {\n", "\n", " fixmeIvy('FW-738: ngtsc doesn\\'t generate flat index files')\n", " .it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n", "\n", " it('should not have amd module names',\n", " () => { expect(shx.cat('public_api.d.ts')).not.toContain('<amd-module name'); });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n" ], "file_path": "packages/bazel/test/ng_package/core_package.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
<!doctype html> <html> <head> <title>protractor test</title> </head> <body> <script src="/bundle.min.js"></script> </body> </html>
packages/bazel/test/protractor-2/index.html
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.0001737863931339234, 0.0001737863931339234, 0.0001737863931339234, 0.0001737863931339234, 0 ]
{ "id": 2, "code_window": [ " });\n", "\n", "\n", " describe('typescript support', () => {\n", "\n", " fixmeIvy('FW-738: ngtsc doesn\\'t generate flat index files')\n", " .it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n", "\n", " it('should not have amd module names',\n", " () => { expect(shx.cat('public_api.d.ts')).not.toContain('<amd-module name'); });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n" ], "file_path": "packages/bazel/test/ng_package/core_package.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
/** * @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 {TestBed} from '@angular/core/testing'; import {RouterTestingModule} from '@angular/router/testing'; import {Observable, Observer, of } from 'rxjs'; import {every, mergeMap} from 'rxjs/operators'; import {TestScheduler} from 'rxjs/testing'; import {prioritizedGuardValue} from '../../src/operators/prioritized_guard_value'; import {Router} from '../../src/router'; import {UrlTree} from '../../src/url_tree'; describe('prioritizedGuardValue operator', () => { let testScheduler: TestScheduler; let router: Router; const TF = {T: true, F: false}; beforeEach(() => { TestBed.configureTestingModule({imports: [RouterTestingModule]}); }); beforeEach(() => { testScheduler = new TestScheduler(assertDeepEquals); }); beforeEach(() => { router = TestBed.get(Router); }); it('should return true if all values are true', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' ----------(T|)', TF); const c = cold(' ------(T|)', TF); const source = hot('---o--', {o: [a, b, c]}); const expected = ' -------------T--'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, TF, /* an error here maybe */); }); }); it('should return false if observables to the left of false have produced a value', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' ----------(T|)', TF); const c = cold(' ------(F|)', TF); const source = hot('---o--', {o: [a, b, c]}); const expected = ' -------------F--'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, TF, /* an error here maybe */); }); }); it('should ignore results for unresolved sets of Observables', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' -------------(T|)', TF); const c = cold(' ------(F|)', TF); const z = cold(' ----(T|)', TF); const source = hot('---o----p----', {o: [a, b, c], p: [z]}); const expected = ' ------------T---'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, TF, /* an error here maybe */); }); }); it('should return UrlTree if higher priority guards have resolved', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTree = router.parseUrl('/'); const urlLookup = {U: urlTree}; const a = cold(' --(T|)', TF); const b = cold(' ----------(U|)', urlLookup); const c = cold(' ------(T|)', TF); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------U---'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, urlLookup, /* an error here maybe */); }); }); it('should return false even with UrlTree if UrlTree is lower priority', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTree = router.parseUrl('/'); const urlLookup = {U: urlTree}; const a = cold(' --(T|)', TF); const b = cold(' ----------(F|)', TF); const c = cold(' ------(U|)', urlLookup); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------F---'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, TF, /* an error here maybe */); }); }); it('should return UrlTree even after a false if the false is lower priority', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTree = router.parseUrl('/'); const urlLookup = {U: urlTree}; const a = cold(' --(T|)', TF); const b = cold(' ----------(U|)', urlLookup); const c = cold(' ------(F|)', TF); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------U----'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, urlLookup, /* an error here maybe */); }); }); it('should return the highest priority UrlTree', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTreeU = router.parseUrl('/u'); const urlTreeR = router.parseUrl('/r'); const urlTreeL = router.parseUrl('/l'); const urlLookup = {U: urlTreeU, R: urlTreeR, L: urlTreeL}; const a = cold(' ----------(U|)', urlLookup); const b = cold(' -----(R|)', urlLookup); const c = cold(' --(L|)', urlLookup); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------U---'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, urlLookup, /* an error here maybe */); }); }); it('should propagate errors', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' ------#', TF); const c = cold(' ----------(F|)', TF); const source = hot('---o------', {o: [a, b, c]}); const expected = ' ---------#'; expectObservable(source.pipe(prioritizedGuardValue())) .toBe(expected, TF, /* an error here maybe */); }); }); }); function assertDeepEquals(a: any, b: any) { return expect(a).toEqual(b); }
packages/router/test/operators/prioritized_guard_value.spec.ts
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00017829016724135727, 0.0001748049253365025, 0.0001662986323935911, 0.00017541726992931217, 0.000002551467332523316 ]
{ "id": 2, "code_window": [ " });\n", "\n", "\n", " describe('typescript support', () => {\n", "\n", " fixmeIvy('FW-738: ngtsc doesn\\'t generate flat index files')\n", " .it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n", "\n", " it('should not have amd module names',\n", " () => { expect(shx.cat('public_api.d.ts')).not.toContain('<amd-module name'); });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should have an index d.ts file',\n", " () => { expect(shx.cat('core.d.ts')).toContain(`export *`); });\n" ], "file_path": "packages/bazel/test/ng_package/core_package.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
// Imports import fetch from 'node-fetch'; import {assertNotMissingOrEmpty} from './utils'; // Constants const CIRCLE_CI_API_URL = 'https://circleci.com/api/v1.1/project/github'; // Interfaces - Types export interface ArtifactInfo { path: string; pretty_path: string; node_index: number; url: string; } export type ArtifactResponse = ArtifactInfo[]; export interface BuildInfo { reponame: string; failed: boolean; branch: string; username: string; build_num: number; has_artifacts: boolean; outcome: string; // e.g. 'success' vcs_revision: string; // HEAD SHA // there are other fields but they are not used in this code } /** * A Helper that can interact with the CircleCI API. */ export class CircleCiApi { private tokenParam = `circle-token=${this.circleCiToken}`; /** * Construct a helper that can interact with the CircleCI REST API. * @param githubOrg The Github organisation whose repos we want to access in CircleCI (e.g. angular). * @param githubRepo The Github repo whose builds we want to access in CircleCI (e.g. angular). * @param circleCiToken The CircleCI API access token (secret). */ constructor( private githubOrg: string, private githubRepo: string, private circleCiToken: string, ) { assertNotMissingOrEmpty('githubOrg', githubOrg); assertNotMissingOrEmpty('githubRepo', githubRepo); assertNotMissingOrEmpty('circleCiToken', circleCiToken); } /** * Get the info for a build from the CircleCI API * @param buildNumber The CircleCI build number that generated the artifact. * @returns A promise to the info about the build */ public async getBuildInfo(buildNumber: number): Promise<BuildInfo> { try { const baseUrl = `${CIRCLE_CI_API_URL}/${this.githubOrg}/${this.githubRepo}/${buildNumber}`; const response = await fetch(`${baseUrl}?${this.tokenParam}`); if (response.status !== 200) { throw new Error(`${baseUrl}: ${response.status} - ${response.statusText}`); } return response.json(); } catch (error) { throw new Error(`CircleCI build info request failed (${error.message})`); } } /** * Query the CircleCI API to get a URL for a specified artifact from a specified build. * @param artifactPath The path, within the build to the artifact. * @returns A promise to the URL that can be requested to download the actual build artifact file. */ public async getBuildArtifactUrl(buildNumber: number, artifactPath: string): Promise<string> { const baseUrl = `${CIRCLE_CI_API_URL}/${this.githubOrg}/${this.githubRepo}/${buildNumber}`; try { const response = await fetch(`${baseUrl}/artifacts?${this.tokenParam}`); const artifacts = await response.json() as ArtifactResponse; const artifact = artifacts.find(item => item.path === artifactPath); if (!artifact) { throw new Error(`Missing artifact (${artifactPath}) for CircleCI build: ${buildNumber}`); } return artifact.url; } catch (error) { throw new Error(`CircleCI artifact URL request failed (${error.message})`); } } }
aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts
0
https://github.com/angular/angular/commit/6b9693157654bc148955f5b8eba29db2d829aabc
[ 0.00017838896019384265, 0.00017374521121382713, 0.0001690094795776531, 0.00017445080447942019, 0.0000028791400836780667 ]
{ "id": 0, "code_window": [ "\n", " const url = new URL(event.request.url)\n", "\n", " const r = await localCall({\n", " event,\n", " url: url.pathname,\n", " host: url.hostname,\n", " protocol: url.protocol,\n", " headers: event.request.headers,\n", " method: event.request.method,\n", " redirect: event.request.redirect,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: url.pathname + url.search,\n" ], "file_path": "packages/nitro/src/runtime/entries/cloudflare.ts", "type": "replace", "edit_start_line_idx": 21 }
import '~polyfill' import { localCall } from '../server' export async function handler (event, context) { const r = await localCall({ event, url: event.path, context, headers: event.headers, method: event.httpMethod, query: event.queryStringParameters, body: event.body // TODO: handle event.isBase64Encoded }) return { statusCode: r.status, headers: r.headers, body: r.body.toString() } }
packages/nitro/src/runtime/entries/lambda.ts
1
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.9717566967010498, 0.4403100311756134, 0.00017038598889485002, 0.3490031063556671, 0.4018687307834625 ]
{ "id": 0, "code_window": [ "\n", " const url = new URL(event.request.url)\n", "\n", " const r = await localCall({\n", " event,\n", " url: url.pathname,\n", " host: url.hostname,\n", " protocol: url.protocol,\n", " headers: event.request.headers,\n", " method: event.request.method,\n", " redirect: event.request.redirect,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: url.pathname + url.search,\n" ], "file_path": "packages/nitro/src/runtime/entries/cloudflare.ts", "type": "replace", "edit_start_line_idx": 21 }
import fetch from 'node-fetch' import { resolve } from 'upath' import { build, generate, prepare } from './build' import { getNitroContext, NitroContext } from './context' import { createDevServer } from './server/dev' import { wpfs } from './utils/wpfs' import { resolveMiddleware } from './server/middleware' export default function nuxt2CompatModule () { const { nuxt } = this // Ensure we're not just building with 'static' target if (!nuxt.options.dev && nuxt.options.target === 'static' && !nuxt.options._export && !nuxt.options._legacyGenerate) { throw new Error('[nitro] Please use `nuxt generate` for static target') } // Disable loading-screen nuxt.options.build.loadingScreen = false nuxt.options.build.indicator = false // Create contexts const nitroContext = getNitroContext(nuxt.options, nuxt.options.nitro || {}) const nitroDevContext = getNitroContext(nuxt.options, { preset: 'dev' }) // Connect hooks nuxt.addHooks(nitroContext.nuxtHooks) nuxt.hook('close', () => nitroContext._internal.hooks.callHook('close')) nuxt.addHooks(nitroDevContext.nuxtHooks) nuxt.hook('close', () => nitroDevContext._internal.hooks.callHook('close')) nitroDevContext._internal.hooks.hook('renderLoading', (req, res) => nuxt.callHook('server:nuxt:renderLoading', req, res)) // Expose process.env.NITRO_PRESET nuxt.options.env.NITRO_PRESET = nitroContext.preset // .ts is supported for serverMiddleware nuxt.options.extensions.push('ts') // Replace nuxt server if (nuxt.server) { nuxt.server.__closed = true nuxt.server = createNuxt2DevServer(nitroDevContext) } // Disable server sourceMap, esbuild will generate for it. nuxt.hook('webpack:config', (webpackConfigs) => { const serverConfig = webpackConfigs.find(config => config.name === 'server') serverConfig.devtool = false }) // Nitro client plugin this.addPlugin({ fileName: 'nitro.client.js', src: resolve(nitroContext._internal.runtimeDir, 'app/nitro.client.js') }) // Resolve middleware nuxt.hook('modules:done', () => { const { middleware, legacyMiddleware } = resolveMiddleware(nuxt.options.serverMiddleware, nuxt.resolver.resolvePath) if (nuxt.server) { nuxt.server.setLegacyMiddleware(legacyMiddleware) } nitroContext.middleware.push(...middleware) nitroDevContext.middleware.push(...middleware) }) // nuxt build/dev nuxt.options.build._minifyServer = false nuxt.options.build.standalone = false nuxt.hook('build:done', async () => { if (nuxt.options.dev) { await build(nitroDevContext) } else if (!nitroContext._nuxt.isStatic) { await prepare(nitroContext) await generate(nitroContext) await build(nitroContext) } }) // nude dev if (nuxt.options.dev) { nitroDevContext._internal.hooks.hook('nitro:compiled', () => { nuxt.server.watch() }) nuxt.hook('build:compile', ({ compiler }) => { compiler.outputFileSystem = wpfs }) nuxt.hook('server:devMiddleware', (m) => { nuxt.server.setDevMiddleware(m) }) } // nuxt generate nuxt.options.generate.dir = nitroContext.output.publicDir nuxt.options.generate.manifest = false nuxt.hook('generate:cache:ignore', (ignore: string[]) => { ignore.push(nitroContext.output.dir) ignore.push(nitroContext.output.serverDir) if (nitroContext.output.publicDir) { ignore.push(nitroContext.output.publicDir) } ignore.push(...nitroContext.ignore) }) nuxt.hook('generate:before', async () => { await prepare(nitroContext) }) nuxt.hook('generate:extendRoutes', async () => { await build(nitroDevContext) await nuxt.server.reload() }) nuxt.hook('generate:done', async () => { await nuxt.server.close() await build(nitroContext) }) } function createNuxt2DevServer (nitroContext: NitroContext) { const server = createDevServer(nitroContext) const listeners = [] async function listen (port) { const listener = await server.listen(port, { showURL: false, isProd: true }) listeners.push(listener) return listener } async function renderRoute (route = '/', renderContext = {}) { const [listener] = listeners if (!listener) { throw new Error('There is no server listener to call `server.renderRoute()`') } const html = await fetch(listener.url + route, { headers: { 'nuxt-render-context': encodeQuery(renderContext) } }).then(r => r.text()) return { html } } return { ...server, listeners, renderRoute, listen, serverMiddlewarePaths () { return [] }, ready () { } } } function encodeQuery (obj) { return Object.entries(obj).map( ([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(val))}` ).join('&') }
packages/nitro/src/compat.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.004539987538009882, 0.00044417171739041805, 0.0001662127033341676, 0.0001714932732284069, 0.0010575399501249194 ]
{ "id": 0, "code_window": [ "\n", " const url = new URL(event.request.url)\n", "\n", " const r = await localCall({\n", " event,\n", " url: url.pathname,\n", " host: url.hostname,\n", " protocol: url.protocol,\n", " headers: event.request.headers,\n", " method: event.request.method,\n", " redirect: event.request.redirect,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: url.pathname + url.search,\n" ], "file_path": "packages/nitro/src/runtime/entries/cloudflare.ts", "type": "replace", "edit_start_line_idx": 21 }
// import ansiHTML from 'ansi-html' const cwd = process.cwd() // TODO: Handle process.env.DEBUG export function handleError (error, req, res) { const stack = (error.stack || '') .split('\n') .splice(1) .filter(line => line.includes('at ')) .map((line) => { const text = line .replace(cwd + '/', './') .replace('webpack:/', '') .replace('.vue', '.js') // TODO: Support sourcemap .trim() return { text, internal: (line.includes('node_modules') && !line.includes('.cache')) || line.includes('internal') || line.includes('new Promise') } }) console.error(error.message + '\n' + stack.map(l => ' ' + l.text).join(' \n')) const html = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Nuxt Error</title> <style> html, body { background: white; color: red; font-family: monospace; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100%; } .stack { padding-left: 2em; } .stack.internal { color: grey; } </style> </head> <body> <div> <div>${req.method} ${req.url}</div><br> <h1>${error.toString()}</h1> <pre>${stack.map(i => `<span class="stack${i.internal ? ' internal' : ''}">${i.text}</span>` ).join('\n') }</pre> </div> </body> </html> ` res.statusCode = error.statusCode || 500 res.statusMessage = error.statusMessage || 'Internal Error' res.end(html) }
packages/nitro/src/runtime/server/error.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.00017445598496124148, 0.00017181613657157868, 0.00016827526269480586, 0.00017236698477063328, 0.0000022316366994346026 ]
{ "id": 0, "code_window": [ "\n", " const url = new URL(event.request.url)\n", "\n", " const r = await localCall({\n", " event,\n", " url: url.pathname,\n", " host: url.hostname,\n", " protocol: url.protocol,\n", " headers: event.request.headers,\n", " method: event.request.method,\n", " redirect: event.request.redirect,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: url.pathname + url.search,\n" ], "file_path": "packages/nitro/src/runtime/entries/cloudflare.ts", "type": "replace", "edit_start_line_idx": 21 }
import type { $Fetch } from 'ohmyfetch' declare global { const $fetch: $Fetch namespace NodeJS { interface Global { $fetch: $Fetch } } }
packages/nitro/src/types.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.00017081803525798023, 0.0001690707285888493, 0.0001673234364716336, 0.0001690707285888493, 0.0000017472993931733072 ]
{ "id": 1, "code_window": [ "import '~polyfill'\n", "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { withQuery } from 'ufo'\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "add", "edit_start_line_idx": 1 }
import '~polyfill' import { localCall } from '../server' export async function handler (event, context) { const r = await localCall({ event, url: event.path, context, headers: event.headers, method: event.httpMethod, query: event.queryStringParameters, body: event.body // TODO: handle event.isBase64Encoded }) return { statusCode: r.status, headers: r.headers, body: r.body.toString() } }
packages/nitro/src/runtime/entries/lambda.ts
1
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.9686103463172913, 0.3229934871196747, 0.00017991079948842525, 0.00019018450984731317, 0.45652008056640625 ]
{ "id": 1, "code_window": [ "import '~polyfill'\n", "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { withQuery } from 'ufo'\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "add", "edit_start_line_idx": 1 }
import '~polyfill' import { localCall } from '../server' export default async function handle (context, req) { const url = '/' + (req.params.url || '') const { body, status, statusText, headers } = await localCall({ url, headers: req.headers, method: req.method, body: req.body }) context.res = { status, headers, body: body ? body.toString() : statusText } }
packages/nitro/src/runtime/entries/azure_functions.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.09439370036125183, 0.047281891107559204, 0.00017008195572998375, 0.047281891107559204, 0.04711180925369263 ]
{ "id": 1, "code_window": [ "import '~polyfill'\n", "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { withQuery } from 'ufo'\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "add", "edit_start_line_idx": 1 }
// @ts-ignore import { createRenderer } from '~vueServerRenderer' const _renderer = createRenderer({}) export function renderToString (component, context) { return new Promise((resolve, reject) => { _renderer.renderToString(component, context, (err, result) => { if (err) { return reject(err) } return resolve(result) }) }) }
packages/nitro/src/runtime/app/vue2.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.00017301870684605092, 0.0001713530218694359, 0.00016968735144473612, 0.0001713530218694359, 0.0000016656777006573975 ]
{ "id": 1, "code_window": [ "import '~polyfill'\n", "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { withQuery } from 'ufo'\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "add", "edit_start_line_idx": 1 }
import { resolve } from 'upath' import { extendPreset, writeFile } from '../utils' import { NitroPreset, NitroContext } from '../context' import { node } from './node' export const vercel: NitroPreset = extendPreset(node, { entry: '{{ _internal.runtimeDir }}/entries/vercel', output: { dir: '{{ _nuxt.rootDir }}/.vercel_build_output', serverDir: '{{ output.dir }}/functions/node/server', publicDir: '{{ output.dir }}/static' }, ignore: [ 'vercel.json' ], hooks: { async 'nitro:compiled' (ctx: NitroContext) { await writeRoutes(ctx) } } }) async function writeRoutes ({ output }: NitroContext) { const routes = [ { src: '/sw.js', headers: { 'cache-control': 'public, max-age=0, must-revalidate' }, continue: true }, { src: '/_nuxt/(.*)', headers: { 'cache-control': 'public,max-age=31536000,immutable' }, continue: true }, { handle: 'filesystem' }, { src: '(.*)', dest: '/.vercel/functions/server/index' } ] await writeFile(resolve(output.dir, 'config/routes.json'), JSON.stringify(routes, null, 2)) }
packages/nitro/src/presets/vercel.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.00028413787367753685, 0.00019077211618423462, 0.000163252858328633, 0.00016793928807601333, 0.00004675743912230246 ]
{ "id": 2, "code_window": [ "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n", " const r = await localCall({\n", " event,\n", " url: event.path,\n", " context,\n", " headers: event.headers,\n", " method: event.httpMethod,\n", " query: event.queryStringParameters,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: withQuery(event.path, event.queryStringParameters),\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "replace", "edit_start_line_idx": 6 }
import '~polyfill' import { localCall } from '../server' export async function handler (event, context) { const r = await localCall({ event, url: event.path, context, headers: event.headers, method: event.httpMethod, query: event.queryStringParameters, body: event.body // TODO: handle event.isBase64Encoded }) return { statusCode: r.status, headers: r.headers, body: r.body.toString() } }
packages/nitro/src/runtime/entries/lambda.ts
1
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.9980892539024353, 0.6632674336433411, 0.00017037054931279272, 0.9915426969528198, 0.4688880741596222 ]
{ "id": 2, "code_window": [ "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n", " const r = await localCall({\n", " event,\n", " url: event.path,\n", " context,\n", " headers: event.headers,\n", " method: event.httpMethod,\n", " query: event.queryStringParameters,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: withQuery(event.path, event.queryStringParameters),\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "replace", "edit_start_line_idx": 6 }
import createEtag from 'etag' import { readFileSync, statSync } from 'fs-extra' import mime from 'mime' import { relative, resolve } from 'upath' import virtual from '@rollup/plugin-virtual' import globby from 'globby' import type { Plugin } from 'rollup' import type { NitroContext } from '../../context' export function staticAssets (context: NitroContext) { const assets: Record<string, { type: string, etag: string, mtime: string, path: string }> = {} const files = globby.sync('**/*.*', { cwd: context.output.publicDir, absolute: false }) for (const id of files) { let type = mime.getType(id) || 'text/plain' if (type.startsWith('text')) { type += '; charset=utf-8' } const fullPath = resolve(context.output.publicDir, id) const etag = createEtag(readFileSync(fullPath)) const stat = statSync(fullPath) assets['/' + id] = { type, etag, mtime: stat.mtime.toJSON(), path: relative(context.output.serverDir, fullPath) } } return virtual({ '~static-assets': `export default ${JSON.stringify(assets, null, 2)};`, '~static': ` import { promises } from 'fs' import { resolve } from 'path' import assets from '~static-assets' export function readAsset (id) { return promises.readFile(resolve(mainDir, getAsset(id).path)) } export function getAsset (id) { return assets[id] } ` }) } export function dirnames (): Plugin { return { name: 'dirnames', renderChunk (code, chunk) { return { code: code + (chunk.isEntry ? 'global.mainDir="undefined"!=typeof __dirname?__dirname:require.main.filename;' : ''), map: null } } } }
packages/nitro/src/rollup/plugins/static.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.00025253440253436565, 0.00018501044542063028, 0.0001673101942287758, 0.00017262491746805608, 0.000030273724405560642 ]
{ "id": 2, "code_window": [ "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n", " const r = await localCall({\n", " event,\n", " url: event.path,\n", " context,\n", " headers: event.headers,\n", " method: event.httpMethod,\n", " query: event.queryStringParameters,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: withQuery(event.path, event.queryStringParameters),\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "replace", "edit_start_line_idx": 6 }
import '~polyfill' import { localCall } from '../server' export default async function handle (context, req) { const url = '/' + (req.params.url || '') const { body, status, statusText, headers } = await localCall({ url, headers: req.headers, method: req.method, body: req.body }) context.res = { status, headers, body: body ? body.toString() : statusText } }
packages/nitro/src/runtime/entries/azure_functions.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.004485575016587973, 0.0023775757290422916, 0.00026957629597745836, 0.0023775757290422916, 0.0021079995203763247 ]
{ "id": 2, "code_window": [ "import { localCall } from '../server'\n", "\n", "export async function handler (event, context) {\n", " const r = await localCall({\n", " event,\n", " url: event.path,\n", " context,\n", " headers: event.headers,\n", " method: event.httpMethod,\n", " query: event.queryStringParameters,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " url: withQuery(event.path, event.queryStringParameters),\n" ], "file_path": "packages/nitro/src/runtime/entries/lambda.ts", "type": "replace", "edit_start_line_idx": 6 }
import '~polyfill' import { Server } from 'http' import destr from 'destr' import { handle } from '../server' const server = new Server(handle) const port = (destr(process.env.NUXT_PORT || process.env.PORT) || 3000) as number const hostname = process.env.NUXT_HOST || process.env.HOST || 'localhost' // @ts-ignore server.listen(port, hostname, (err) => { if (err) { console.error(err) process.exit(1) } console.log(`Listening on http://${hostname}:${port}`) }) export default {}
packages/nitro/src/runtime/entries/server.ts
0
https://github.com/nuxt/nuxt/commit/8cc836ebf6b19702f961791c618a1ab6b4bb7ae4
[ 0.003101054346188903, 0.0011462492402642965, 0.0001673231163294986, 0.00017037037468980998, 0.0013822565088048577 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tinitData.environment.extensionTestsLocationURI = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTestsLocationURI));\n", "\t\tinitData.environment.globalStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.globalStorageHome));\n", "\t\tinitData.environment.workspaceStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.workspaceStorageHome));\n", "\t\tinitData.nlsBaseUrl = URI.revive(rpcProtocol.transformIncomingURIs(initData.nlsBaseUrl));\n", "\t\tinitData.logsLocation = URI.revive(rpcProtocol.transformIncomingURIs(initData.logsLocation));\n", "\t\tinitData.logFile = URI.revive(rpcProtocol.transformIncomingURIs(initData.logFile));\n", "\t\tinitData.workspace = rpcProtocol.transformIncomingURIs(initData.workspace);\n", "\t\treturn initData;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinitData.environment.extensionTelemetryLogResource = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTelemetryLogResource));\n" ], "file_path": "src/vs/workbench/api/common/extensionHostMain.ts", "type": "add", "edit_start_line_idx": 180 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Schemas } from 'vs/base/common/network'; import { joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ExtensionKind, IEnvironmentService, IExtensionHostDebugParams } from 'vs/platform/environment/common/environment'; import { IPath } from 'vs/platform/window/common/window'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IWorkbenchConstructionOptions } from 'vs/workbench/browser/web.api'; import { IProductService } from 'vs/platform/product/common/productService'; import { memoize } from 'vs/base/common/decorators'; import { onUnexpectedError } from 'vs/base/common/errors'; import { parseLineAndColumnAware } from 'vs/base/common/extpath'; import { LogLevelToString } from 'vs/platform/log/common/log'; import { isUndefined } from 'vs/base/common/types'; import { refineServiceDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { EXTENSION_IDENTIFIER_WITH_LOG_REGEX } from 'vs/platform/environment/common/environmentService'; export const IBrowserWorkbenchEnvironmentService = refineServiceDecorator<IEnvironmentService, IBrowserWorkbenchEnvironmentService>(IEnvironmentService); /** * A subclass of the `IWorkbenchEnvironmentService` to be used only environments * where the web API is available (browsers, Electron). */ export interface IBrowserWorkbenchEnvironmentService extends IWorkbenchEnvironmentService { /** * Options used to configure the workbench. */ readonly options?: IWorkbenchConstructionOptions; } export class BrowserWorkbenchEnvironmentService implements IBrowserWorkbenchEnvironmentService { declare readonly _serviceBrand: undefined; @memoize get remoteAuthority(): string | undefined { return this.options.remoteAuthority; } @memoize get isBuilt(): boolean { return !!this.productService.commit; } @memoize get logsPath(): string { return this.logsHome.path; } @memoize get logLevel(): string | undefined { const logLevelFromPayload = this.payload?.get('logLevel'); if (logLevelFromPayload) { return logLevelFromPayload.split(',').find(entry => !EXTENSION_IDENTIFIER_WITH_LOG_REGEX.test(entry)); } return this.options.developmentOptions?.logLevel !== undefined ? LogLevelToString(this.options.developmentOptions?.logLevel) : undefined; } get extensionLogLevel(): [string, string][] | undefined { const logLevelFromPayload = this.payload?.get('logLevel'); if (logLevelFromPayload) { const result: [string, string][] = []; for (const entry of logLevelFromPayload.split(',')) { const matches = EXTENSION_IDENTIFIER_WITH_LOG_REGEX.exec(entry); if (matches && matches[1] && matches[2]) { result.push([matches[1], matches[2]]); } } return result.length ? result : undefined; } return this.options.developmentOptions?.extensionLogLevel !== undefined ? this.options.developmentOptions?.extensionLogLevel.map(([extension, logLevel]) => ([extension, LogLevelToString(logLevel)])) : undefined; } @memoize get windowLogsPath(): URI { return this.logsHome; } @memoize get logFile(): URI { return joinPath(this.windowLogsPath, 'window.log'); } @memoize get userRoamingDataHome(): URI { return URI.file('/User').with({ scheme: Schemas.vscodeUserData }); } @memoize get argvResource(): URI { return joinPath(this.userRoamingDataHome, 'argv.json'); } @memoize get cacheHome(): URI { return joinPath(this.userRoamingDataHome, 'caches'); } @memoize get workspaceStorageHome(): URI { return joinPath(this.userRoamingDataHome, 'workspaceStorage'); } @memoize get localHistoryHome(): URI { return joinPath(this.userRoamingDataHome, 'History'); } @memoize get stateResource(): URI { return joinPath(this.userRoamingDataHome, 'State', 'storage.json'); } /** * In Web every workspace can potentially have scoped user-data * and/or extensions and if Sync state is shared then it can make * Sync error prone - say removing extensions from another workspace. * Hence scope Sync state per workspace. Sync scoped to a workspace * is capable of handling opening same workspace in multiple windows. */ @memoize get userDataSyncHome(): URI { return joinPath(this.userRoamingDataHome, 'sync', this.workspaceId); } @memoize get userDataSyncLogResource(): URI { return joinPath(this.logsHome, 'userDataSync.log'); } @memoize get editSessionsLogResource(): URI { return joinPath(this.logsHome, 'editSessions.log'); } @memoize get remoteTunnelLogResource(): URI { return joinPath(this.logsHome, 'remoteTunnel.log'); } @memoize get sync(): 'on' | 'off' | undefined { return undefined; } @memoize get keyboardLayoutResource(): URI { return joinPath(this.userRoamingDataHome, 'keyboardLayout.json'); } @memoize get untitledWorkspacesHome(): URI { return joinPath(this.userRoamingDataHome, 'Workspaces'); } @memoize get serviceMachineIdResource(): URI { return joinPath(this.userRoamingDataHome, 'machineid'); } @memoize get extHostLogsPath(): URI { return joinPath(this.logsHome, 'exthost'); } @memoize get extHostTelemetryLogFile(): URI { return joinPath(this.extHostLogsPath, 'telemetry.log'); } private extensionHostDebugEnvironment: IExtensionHostDebugEnvironment | undefined = undefined; @memoize get debugExtensionHost(): IExtensionHostDebugParams { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.params; } @memoize get isExtensionDevelopment(): boolean { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.isExtensionDevelopment; } @memoize get extensionDevelopmentLocationURI(): URI[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionDevelopmentLocationURI; } @memoize get extensionDevelopmentLocationKind(): ExtensionKind[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionDevelopmentKind; } @memoize get extensionTestsLocationURI(): URI | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionTestsLocationURI; } @memoize get extensionEnabledProposedApi(): string[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionEnabledProposedApi; } @memoize get debugRenderer(): boolean { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.debugRenderer; } @memoize get enableSmokeTestDriver() { return this.options.developmentOptions?.enableSmokeTestDriver; } @memoize get disableExtensions() { return this.payload?.get('disableExtensions') === 'true'; } @memoize get enableExtensions() { return this.options.enabledExtensions; } @memoize get webviewExternalEndpoint(): string { const endpoint = this.options.webviewEndpoint || this.productService.webviewContentExternalBaseUrlTemplate || 'https://{{uuid}}.vscode-cdn.net/{{quality}}/{{commit}}/out/vs/workbench/contrib/webview/browser/pre/'; const webviewExternalEndpointCommit = this.payload?.get('webviewExternalEndpointCommit'); return endpoint .replace('{{commit}}', webviewExternalEndpointCommit ?? this.productService.commit ?? 'ef65ac1ba57f57f2a3961bfe94aa20481caca4c6') .replace('{{quality}}', (webviewExternalEndpointCommit ? 'insider' : this.productService.quality) ?? 'insider'); } @memoize get telemetryLogResource(): URI { return joinPath(this.logsHome, 'telemetry.log'); } get extensionTelemetryLogResource(): URI { return joinPath(this.logsHome, 'extensionTelemetry.log'); } @memoize get disableTelemetry(): boolean { return false; } @memoize get verbose(): boolean { return this.payload?.get('verbose') === 'true'; } @memoize get logExtensionHostCommunication(): boolean { return this.payload?.get('logExtensionHostCommunication') === 'true'; } @memoize get skipReleaseNotes(): boolean { return this.payload?.get('skipReleaseNotes') === 'true'; } @memoize get skipWelcome(): boolean { return this.payload?.get('skipWelcome') === 'true'; } @memoize get disableWorkspaceTrust(): boolean { return !this.options.enableWorkspaceTrust; } @memoize get lastActiveProfile(): string | undefined { return this.payload?.get('lastActiveProfile'); } editSessionId: string | undefined = this.options.editSessionId; private payload: Map<string, string> | undefined; constructor( private readonly workspaceId: string, private readonly logsHome: URI, readonly options: IWorkbenchConstructionOptions, private readonly productService: IProductService ) { if (options.workspaceProvider && Array.isArray(options.workspaceProvider.payload)) { try { this.payload = new Map(options.workspaceProvider.payload); } catch (error) { onUnexpectedError(error); // possible invalid payload for map } } } private resolveExtensionHostDebugEnvironment(): IExtensionHostDebugEnvironment { const extensionHostDebugEnvironment: IExtensionHostDebugEnvironment = { params: { port: null, break: false }, debugRenderer: false, isExtensionDevelopment: false, extensionDevelopmentLocationURI: undefined, extensionDevelopmentKind: undefined }; // Fill in selected extra environmental properties if (this.payload) { for (const [key, value] of this.payload) { switch (key) { case 'extensionDevelopmentPath': if (!extensionHostDebugEnvironment.extensionDevelopmentLocationURI) { extensionHostDebugEnvironment.extensionDevelopmentLocationURI = []; } extensionHostDebugEnvironment.extensionDevelopmentLocationURI.push(URI.parse(value)); extensionHostDebugEnvironment.isExtensionDevelopment = true; break; case 'extensionDevelopmentKind': extensionHostDebugEnvironment.extensionDevelopmentKind = [<ExtensionKind>value]; break; case 'extensionTestsPath': extensionHostDebugEnvironment.extensionTestsLocationURI = URI.parse(value); break; case 'debugRenderer': extensionHostDebugEnvironment.debugRenderer = value === 'true'; break; case 'debugId': extensionHostDebugEnvironment.params.debugId = value; break; case 'inspect-brk-extensions': extensionHostDebugEnvironment.params.port = parseInt(value); extensionHostDebugEnvironment.params.break = true; break; case 'inspect-extensions': extensionHostDebugEnvironment.params.port = parseInt(value); break; case 'enableProposedApi': extensionHostDebugEnvironment.extensionEnabledProposedApi = []; break; } } } const developmentOptions = this.options.developmentOptions; if (developmentOptions && !extensionHostDebugEnvironment.isExtensionDevelopment) { if (developmentOptions.extensions?.length) { extensionHostDebugEnvironment.extensionDevelopmentLocationURI = developmentOptions.extensions.map(e => URI.revive(e)); extensionHostDebugEnvironment.isExtensionDevelopment = true; } if (developmentOptions.extensionTestsPath) { extensionHostDebugEnvironment.extensionTestsLocationURI = URI.revive(developmentOptions.extensionTestsPath); } } return extensionHostDebugEnvironment; } @memoize get filesToOpenOrCreate(): IPath<ITextEditorOptions>[] | undefined { if (this.payload) { const fileToOpen = this.payload.get('openFile'); if (fileToOpen) { const fileUri = URI.parse(fileToOpen); // Support: --goto parameter to open on line/col if (this.payload.has('gotoLineMode')) { const pathColumnAware = parseLineAndColumnAware(fileUri.path); return [{ fileUri: fileUri.with({ path: pathColumnAware.path }), options: { selection: !isUndefined(pathColumnAware.line) ? { startLineNumber: pathColumnAware.line, startColumn: pathColumnAware.column || 1 } : undefined } }]; } return [{ fileUri }]; } } return undefined; } @memoize get filesToDiff(): IPath[] | undefined { if (this.payload) { const fileToDiffPrimary = this.payload.get('diffFilePrimary'); const fileToDiffSecondary = this.payload.get('diffFileSecondary'); if (fileToDiffPrimary && fileToDiffSecondary) { return [ { fileUri: URI.parse(fileToDiffSecondary) }, { fileUri: URI.parse(fileToDiffPrimary) } ]; } } return undefined; } @memoize get filesToMerge(): IPath[] | undefined { if (this.payload) { const fileToMerge1 = this.payload.get('mergeFile1'); const fileToMerge2 = this.payload.get('mergeFile2'); const fileToMergeBase = this.payload.get('mergeFileBase'); const fileToMergeResult = this.payload.get('mergeFileResult'); if (fileToMerge1 && fileToMerge2 && fileToMergeBase && fileToMergeResult) { return [ { fileUri: URI.parse(fileToMerge1) }, { fileUri: URI.parse(fileToMerge2) }, { fileUri: URI.parse(fileToMergeBase) }, { fileUri: URI.parse(fileToMergeResult) } ]; } } return undefined; } } interface IExtensionHostDebugEnvironment { params: IExtensionHostDebugParams; debugRenderer: boolean; isExtensionDevelopment: boolean; extensionDevelopmentLocationURI?: URI[]; extensionDevelopmentKind?: ExtensionKind[]; extensionTestsLocationURI?: URI; extensionEnabledProposedApi?: string[]; }
src/vs/workbench/services/environment/browser/environmentService.ts
1
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.005349747370928526, 0.0006573392311111093, 0.00016337806300725788, 0.00018737727077677846, 0.0010355538688600063 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tinitData.environment.extensionTestsLocationURI = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTestsLocationURI));\n", "\t\tinitData.environment.globalStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.globalStorageHome));\n", "\t\tinitData.environment.workspaceStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.workspaceStorageHome));\n", "\t\tinitData.nlsBaseUrl = URI.revive(rpcProtocol.transformIncomingURIs(initData.nlsBaseUrl));\n", "\t\tinitData.logsLocation = URI.revive(rpcProtocol.transformIncomingURIs(initData.logsLocation));\n", "\t\tinitData.logFile = URI.revive(rpcProtocol.transformIncomingURIs(initData.logFile));\n", "\t\tinitData.workspace = rpcProtocol.transformIncomingURIs(initData.workspace);\n", "\t\treturn initData;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinitData.environment.extensionTelemetryLogResource = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTelemetryLogResource));\n" ], "file_path": "src/vs/workbench/api/common/extensionHostMain.ts", "type": "add", "edit_start_line_idx": 180 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { DisposableStore } from 'vs/base/common/lifecycle'; import * as strings from 'vs/base/common/strings'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorAction, IActionOptions, registerEditorAction, registerEditorContribution, ServicesAccessor } from 'vs/editor/browser/editorExtensions'; import { ShiftCommand } from 'vs/editor/common/commands/shiftCommand'; import { EditorAutoIndentStrategy, EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditOperation, ISingleEditOperation } from 'vs/editor/common/core/editOperation'; import { IRange, Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { ICommand, ICursorStateComputerData, IEditOperationBuilder, IEditorContribution } from 'vs/editor/common/editorCommon'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { EndOfLineSequence, ITextModel } from 'vs/editor/common/model'; import { TextEdit } from 'vs/editor/common/languages'; import { StandardTokenType } from 'vs/editor/common/encodedTokenAttributes'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { IndentConsts } from 'vs/editor/common/languages/supports/indentRules'; import { IModelService } from 'vs/editor/common/services/model'; import * as indentUtils from 'vs/editor/contrib/indentation/browser/indentUtils'; import * as nls from 'vs/nls'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { normalizeIndentation } from 'vs/editor/common/core/indentation'; import { getGoodIndentForLine, getIndentMetadata } from 'vs/editor/common/languages/autoIndent'; export function getReindentEditOperations(model: ITextModel, languageConfigurationService: ILanguageConfigurationService, startLineNumber: number, endLineNumber: number, inheritedIndent?: string): ISingleEditOperation[] { if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) { // Model is empty return []; } const indentationRules = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentationRules; if (!indentationRules) { return []; } endLineNumber = Math.min(endLineNumber, model.getLineCount()); // Skip `unIndentedLinePattern` lines while (startLineNumber <= endLineNumber) { if (!indentationRules.unIndentedLinePattern) { break; } const text = model.getLineContent(startLineNumber); if (!indentationRules.unIndentedLinePattern.test(text)) { break; } startLineNumber++; } if (startLineNumber > endLineNumber - 1) { return []; } const { tabSize, indentSize, insertSpaces } = model.getOptions(); const shiftIndent = (indentation: string, count?: number) => { count = count || 1; return ShiftCommand.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces); }; const unshiftIndent = (indentation: string, count?: number) => { count = count || 1; return ShiftCommand.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces); }; const indentEdits: ISingleEditOperation[] = []; // indentation being passed to lines below let globalIndent: string; // Calculate indentation for the first line // If there is no passed-in indentation, we use the indentation of the first line as base. const currentLineText = model.getLineContent(startLineNumber); let adjustedLineContent = currentLineText; if (inheritedIndent !== undefined && inheritedIndent !== null) { globalIndent = inheritedIndent; const oldIndentation = strings.getLeadingWhitespace(currentLineText); adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length); if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) { globalIndent = unshiftIndent(globalIndent); adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length); } if (currentLineText !== adjustedLineContent) { indentEdits.push(EditOperation.replaceMove(new Selection(startLineNumber, 1, startLineNumber, oldIndentation.length + 1), normalizeIndentation(globalIndent, indentSize, insertSpaces))); } } else { globalIndent = strings.getLeadingWhitespace(currentLineText); } // idealIndentForNextLine doesn't equal globalIndent when there is a line matching `indentNextLinePattern`. let idealIndentForNextLine: string = globalIndent; if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) { idealIndentForNextLine = shiftIndent(idealIndentForNextLine); globalIndent = shiftIndent(globalIndent); } else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) { idealIndentForNextLine = shiftIndent(idealIndentForNextLine); } startLineNumber++; // Calculate indentation adjustment for all following lines for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { const text = model.getLineContent(lineNumber); const oldIndentation = strings.getLeadingWhitespace(text); const adjustedLineContent = idealIndentForNextLine + text.substring(oldIndentation.length); if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) { idealIndentForNextLine = unshiftIndent(idealIndentForNextLine); globalIndent = unshiftIndent(globalIndent); } if (oldIndentation !== idealIndentForNextLine) { indentEdits.push(EditOperation.replaceMove(new Selection(lineNumber, 1, lineNumber, oldIndentation.length + 1), normalizeIndentation(idealIndentForNextLine, indentSize, insertSpaces))); } // calculate idealIndentForNextLine if (indentationRules.unIndentedLinePattern && indentationRules.unIndentedLinePattern.test(text)) { // In reindent phase, if the line matches `unIndentedLinePattern` we inherit indentation from above lines // but don't change globalIndent and idealIndentForNextLine. continue; } else if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) { globalIndent = shiftIndent(globalIndent); idealIndentForNextLine = globalIndent; } else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) { idealIndentForNextLine = shiftIndent(idealIndentForNextLine); } else { idealIndentForNextLine = globalIndent; } } return indentEdits; } export class IndentationToSpacesAction extends EditorAction { public static readonly ID = 'editor.action.indentationToSpaces'; constructor() { super({ id: IndentationToSpacesAction.ID, label: nls.localize('indentationToSpaces', "Convert Indentation to Spaces"), alias: 'Convert Indentation to Spaces', precondition: EditorContextKeys.writable }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const model = editor.getModel(); if (!model) { return; } const modelOpts = model.getOptions(); const selection = editor.getSelection(); if (!selection) { return; } const command = new IndentationToSpacesCommand(selection, modelOpts.tabSize); editor.pushUndoStop(); editor.executeCommands(this.id, [command]); editor.pushUndoStop(); model.updateOptions({ insertSpaces: true }); } } export class IndentationToTabsAction extends EditorAction { public static readonly ID = 'editor.action.indentationToTabs'; constructor() { super({ id: IndentationToTabsAction.ID, label: nls.localize('indentationToTabs', "Convert Indentation to Tabs"), alias: 'Convert Indentation to Tabs', precondition: EditorContextKeys.writable }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const model = editor.getModel(); if (!model) { return; } const modelOpts = model.getOptions(); const selection = editor.getSelection(); if (!selection) { return; } const command = new IndentationToTabsCommand(selection, modelOpts.tabSize); editor.pushUndoStop(); editor.executeCommands(this.id, [command]); editor.pushUndoStop(); model.updateOptions({ insertSpaces: false }); } } export class ChangeIndentationSizeAction extends EditorAction { constructor(private readonly insertSpaces: boolean, opts: IActionOptions) { super(opts); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const quickInputService = accessor.get(IQuickInputService); const modelService = accessor.get(IModelService); const model = editor.getModel(); if (!model) { return; } const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget); const picks = [1, 2, 3, 4, 5, 6, 7, 8].map(n => ({ id: n.toString(), label: n.toString(), // add description for tabSize value set in the configuration description: n === creationOpts.tabSize ? nls.localize('configuredTabSize', "Configured Tab Size") : undefined })); // auto focus the tabSize set for the current editor const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7); setTimeout(() => { quickInputService.pick(picks, { placeHolder: nls.localize({ key: 'selectTabWidth', comment: ['Tab corresponds to the tab key'] }, "Select Tab Size for Current File"), activeItem: picks[autoFocusIndex] }).then(pick => { if (pick) { if (model && !model.isDisposed()) { model.updateOptions({ tabSize: parseInt(pick.label, 10), insertSpaces: this.insertSpaces }); } } }); }, 50/* quick input is sensitive to being opened so soon after another */); } } export class IndentUsingTabs extends ChangeIndentationSizeAction { public static readonly ID = 'editor.action.indentUsingTabs'; constructor() { super(false, { id: IndentUsingTabs.ID, label: nls.localize('indentUsingTabs', "Indent Using Tabs"), alias: 'Indent Using Tabs', precondition: undefined }); } } export class IndentUsingSpaces extends ChangeIndentationSizeAction { public static readonly ID = 'editor.action.indentUsingSpaces'; constructor() { super(true, { id: IndentUsingSpaces.ID, label: nls.localize('indentUsingSpaces', "Indent Using Spaces"), alias: 'Indent Using Spaces', precondition: undefined }); } } export class DetectIndentation extends EditorAction { public static readonly ID = 'editor.action.detectIndentation'; constructor() { super({ id: DetectIndentation.ID, label: nls.localize('detectIndentation', "Detect Indentation from Content"), alias: 'Detect Indentation from Content', precondition: undefined }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const modelService = accessor.get(IModelService); const model = editor.getModel(); if (!model) { return; } const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget); model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize); } } export class ReindentLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.reindentlines', label: nls.localize('editor.reindentlines', "Reindent Lines"), alias: 'Reindent Lines', precondition: EditorContextKeys.writable }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const languageConfigurationService = accessor.get(ILanguageConfigurationService); const model = editor.getModel(); if (!model) { return; } const edits = getReindentEditOperations(model, languageConfigurationService, 1, model.getLineCount()); if (edits.length > 0) { editor.pushUndoStop(); editor.executeEdits(this.id, edits); editor.pushUndoStop(); } } } export class ReindentSelectedLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.reindentselectedlines', label: nls.localize('editor.reindentselectedlines', "Reindent Selected Lines"), alias: 'Reindent Selected Lines', precondition: EditorContextKeys.writable }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const languageConfigurationService = accessor.get(ILanguageConfigurationService); const model = editor.getModel(); if (!model) { return; } const selections = editor.getSelections(); if (selections === null) { return; } const edits: ISingleEditOperation[] = []; for (const selection of selections) { let startLineNumber = selection.startLineNumber; let endLineNumber = selection.endLineNumber; if (startLineNumber !== endLineNumber && selection.endColumn === 1) { endLineNumber--; } if (startLineNumber === 1) { if (startLineNumber === endLineNumber) { continue; } } else { startLineNumber--; } const editOperations = getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber); edits.push(...editOperations); } if (edits.length > 0) { editor.pushUndoStop(); editor.executeEdits(this.id, edits); editor.pushUndoStop(); } } } export class AutoIndentOnPasteCommand implements ICommand { private readonly _edits: { range: IRange; text: string; eol?: EndOfLineSequence }[]; private readonly _initialSelection: Selection; private _selectionId: string | null; constructor(edits: TextEdit[], initialSelection: Selection) { this._initialSelection = initialSelection; this._edits = []; this._selectionId = null; for (const edit of edits) { if (edit.range && typeof edit.text === 'string') { this._edits.push(edit as { range: IRange; text: string; eol?: EndOfLineSequence }); } } } public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void { for (const edit of this._edits) { builder.addEditOperation(Range.lift(edit.range), edit.text); } let selectionIsSet = false; if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) { if (this._edits[0].range.startColumn === this._initialSelection.endColumn && this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) { selectionIsSet = true; this._selectionId = builder.trackSelection(this._initialSelection, true); } else if (this._edits[0].range.endColumn === this._initialSelection.startColumn && this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) { selectionIsSet = true; this._selectionId = builder.trackSelection(this._initialSelection, false); } } if (!selectionIsSet) { this._selectionId = builder.trackSelection(this._initialSelection); } } public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection { return helper.getTrackedSelection(this._selectionId!); } } export class AutoIndentOnPaste implements IEditorContribution { public static readonly ID = 'editor.contrib.autoIndentOnPaste'; private readonly callOnDispose = new DisposableStore(); private readonly callOnModel = new DisposableStore(); constructor( private readonly editor: ICodeEditor, @ILanguageConfigurationService private readonly _languageConfigurationService: ILanguageConfigurationService ) { this.callOnDispose.add(editor.onDidChangeConfiguration(() => this.update())); this.callOnDispose.add(editor.onDidChangeModel(() => this.update())); this.callOnDispose.add(editor.onDidChangeModelLanguage(() => this.update())); } private update(): void { // clean up this.callOnModel.clear(); // we are disabled if (this.editor.getOption(EditorOption.autoIndent) < EditorAutoIndentStrategy.Full || this.editor.getOption(EditorOption.formatOnPaste)) { return; } // no model if (!this.editor.hasModel()) { return; } this.callOnModel.add(this.editor.onDidPaste(({ range }) => { this.trigger(range); })); } private trigger(range: Range): void { const selections = this.editor.getSelections(); if (selections === null || selections.length > 1) { return; } const model = this.editor.getModel(); if (!model) { return; } if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber)) { return; } const autoIndent = this.editor.getOption(EditorOption.autoIndent); const { tabSize, indentSize, insertSpaces } = model.getOptions(); const textEdits: TextEdit[] = []; const indentConverter = { shiftIndent: (indentation: string) => { return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces); }, unshiftIndent: (indentation: string) => { return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces); } }; let startLineNumber = range.startLineNumber; while (startLineNumber <= range.endLineNumber) { if (this.shouldIgnoreLine(model, startLineNumber)) { startLineNumber++; continue; } break; } if (startLineNumber > range.endLineNumber) { return; } let firstLineText = model.getLineContent(startLineNumber); if (!/\S/.test(firstLineText.substring(0, range.startColumn - 1))) { const indentOfFirstLine = getGoodIndentForLine(autoIndent, model, model.getLanguageId(), startLineNumber, indentConverter, this._languageConfigurationService); if (indentOfFirstLine !== null) { const oldIndentation = strings.getLeadingWhitespace(firstLineText); const newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize); const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); if (newSpaceCnt !== oldSpaceCnt) { const newIndent = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces); textEdits.push({ range: new Range(startLineNumber, 1, startLineNumber, oldIndentation.length + 1), text: newIndent }); firstLineText = newIndent + firstLineText.substr(oldIndentation.length); } else { const indentMetadata = getIndentMetadata(model, startLineNumber, this._languageConfigurationService); if (indentMetadata === 0 || indentMetadata === IndentConsts.UNINDENT_MASK) { // we paste content into a line where only contains whitespaces // after pasting, the indentation of the first line is already correct // the first line doesn't match any indentation rule // then no-op. return; } } } } const firstLineNumber = startLineNumber; // ignore empty or ignored lines while (startLineNumber < range.endLineNumber) { if (!/\S/.test(model.getLineContent(startLineNumber + 1))) { startLineNumber++; continue; } break; } if (startLineNumber !== range.endLineNumber) { const virtualModel = { tokenization: { getLineTokens: (lineNumber: number) => { return model.tokenization.getLineTokens(lineNumber); }, getLanguageId: () => { return model.getLanguageId(); }, getLanguageIdAtPosition: (lineNumber: number, column: number) => { return model.getLanguageIdAtPosition(lineNumber, column); }, }, getLineContent: (lineNumber: number) => { if (lineNumber === firstLineNumber) { return firstLineText; } else { return model.getLineContent(lineNumber); } } }; const indentOfSecondLine = getGoodIndentForLine(autoIndent, virtualModel, model.getLanguageId(), startLineNumber + 1, indentConverter, this._languageConfigurationService); if (indentOfSecondLine !== null) { const newSpaceCntOfSecondLine = indentUtils.getSpaceCnt(indentOfSecondLine, tabSize); const oldSpaceCntOfSecondLine = indentUtils.getSpaceCnt(strings.getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize); if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) { const spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine; for (let i = startLineNumber + 1; i <= range.endLineNumber; i++) { const lineContent = model.getLineContent(i); const originalIndent = strings.getLeadingWhitespace(lineContent); const originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize); const newSpacesCnt = originalSpacesCnt + spaceCntOffset; const newIndent = indentUtils.generateIndent(newSpacesCnt, tabSize, insertSpaces); if (newIndent !== originalIndent) { textEdits.push({ range: new Range(i, 1, i, originalIndent.length + 1), text: newIndent }); } } } } } if (textEdits.length > 0) { this.editor.pushUndoStop(); const cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection()!); this.editor.executeCommand('autoIndentOnPaste', cmd); this.editor.pushUndoStop(); } } private shouldIgnoreLine(model: ITextModel, lineNumber: number): boolean { model.tokenization.forceTokenization(lineNumber); const nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber); if (nonWhitespaceColumn === 0) { return true; } const tokens = model.tokenization.getLineTokens(lineNumber); if (tokens.getCount() > 0) { const firstNonWhitespaceTokenIndex = tokens.findTokenIndexAtOffset(nonWhitespaceColumn); if (firstNonWhitespaceTokenIndex >= 0 && tokens.getStandardTokenType(firstNonWhitespaceTokenIndex) === StandardTokenType.Comment) { return true; } } return false; } public dispose(): void { this.callOnDispose.dispose(); this.callOnModel.dispose(); } } function getIndentationEditOperations(model: ITextModel, builder: IEditOperationBuilder, tabSize: number, tabsToSpaces: boolean): void { if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) { // Model is empty return; } let spaces = ''; for (let i = 0; i < tabSize; i++) { spaces += ' '; } const spacesRegExp = new RegExp(spaces, 'gi'); for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) { let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber); if (lastIndentationColumn === 0) { lastIndentationColumn = model.getLineMaxColumn(lineNumber); } if (lastIndentationColumn === 1) { continue; } const originalIndentationRange = new Range(lineNumber, 1, lineNumber, lastIndentationColumn); const originalIndentation = model.getValueInRange(originalIndentationRange); const newIndentation = ( tabsToSpaces ? originalIndentation.replace(/\t/ig, spaces) : originalIndentation.replace(spacesRegExp, '\t') ); builder.addEditOperation(originalIndentationRange, newIndentation); } } export class IndentationToSpacesCommand implements ICommand { private selectionId: string | null = null; constructor(private readonly selection: Selection, private tabSize: number) { } public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void { this.selectionId = builder.trackSelection(this.selection); getIndentationEditOperations(model, builder, this.tabSize, true); } public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection { return helper.getTrackedSelection(this.selectionId!); } } export class IndentationToTabsCommand implements ICommand { private selectionId: string | null = null; constructor(private readonly selection: Selection, private tabSize: number) { } public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void { this.selectionId = builder.trackSelection(this.selection); getIndentationEditOperations(model, builder, this.tabSize, false); } public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection { return helper.getTrackedSelection(this.selectionId!); } } registerEditorContribution(AutoIndentOnPaste.ID, AutoIndentOnPaste); registerEditorAction(IndentationToSpacesAction); registerEditorAction(IndentationToTabsAction); registerEditorAction(IndentUsingTabs); registerEditorAction(IndentUsingSpaces); registerEditorAction(DetectIndentation); registerEditorAction(ReindentLinesAction); registerEditorAction(ReindentSelectedLinesAction);
src/vs/editor/contrib/indentation/browser/indentation.ts
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.0001754278055159375, 0.00016956411127466708, 0.00016440069884993136, 0.0001697792176855728, 0.000002332614485567319 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tinitData.environment.extensionTestsLocationURI = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTestsLocationURI));\n", "\t\tinitData.environment.globalStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.globalStorageHome));\n", "\t\tinitData.environment.workspaceStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.workspaceStorageHome));\n", "\t\tinitData.nlsBaseUrl = URI.revive(rpcProtocol.transformIncomingURIs(initData.nlsBaseUrl));\n", "\t\tinitData.logsLocation = URI.revive(rpcProtocol.transformIncomingURIs(initData.logsLocation));\n", "\t\tinitData.logFile = URI.revive(rpcProtocol.transformIncomingURIs(initData.logFile));\n", "\t\tinitData.workspace = rpcProtocol.transformIncomingURIs(initData.workspace);\n", "\t\treturn initData;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinitData.environment.extensionTelemetryLogResource = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTelemetryLogResource));\n" ], "file_path": "src/vs/workbench/api/common/extensionHostMain.ts", "type": "add", "edit_start_line_idx": 180 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { once } from 'vs/base/common/functional'; import { Iterable } from 'vs/base/common/iterator'; // #region Disposable Tracking /** * Enables logging of potentially leaked disposables. * * A disposable is considered leaked if it is not disposed or not registered as the child of * another disposable. This tracking is very simple an only works for classes that either * extend Disposable or use a DisposableStore. This means there are a lot of false positives. */ const TRACK_DISPOSABLES = false; let disposableTracker: IDisposableTracker | null = null; export interface IDisposableTracker { /** * Is called on construction of a disposable. */ trackDisposable(disposable: IDisposable): void; /** * Is called when a disposable is registered as child of another disposable (e.g. {@link DisposableStore}). * If parent is `null`, the disposable is removed from its former parent. */ setParent(child: IDisposable, parent: IDisposable | null): void; /** * Is called after a disposable is disposed. */ markAsDisposed(disposable: IDisposable): void; /** * Indicates that the given object is a singleton which does not need to be disposed. */ markAsSingleton(disposable: IDisposable): void; } export function setDisposableTracker(tracker: IDisposableTracker | null): void { disposableTracker = tracker; } if (TRACK_DISPOSABLES) { const __is_disposable_tracked__ = '__is_disposable_tracked__'; setDisposableTracker(new class implements IDisposableTracker { trackDisposable(x: IDisposable): void { const stack = new Error('Potentially leaked disposable').stack!; setTimeout(() => { if (!(x as any)[__is_disposable_tracked__]) { console.log(stack); } }, 3000); } setParent(child: IDisposable, parent: IDisposable | null): void { if (child && child !== Disposable.None) { try { (child as any)[__is_disposable_tracked__] = true; } catch { // noop } } } markAsDisposed(disposable: IDisposable): void { if (disposable && disposable !== Disposable.None) { try { (disposable as any)[__is_disposable_tracked__] = true; } catch { // noop } } } markAsSingleton(disposable: IDisposable): void { } }); } function trackDisposable<T extends IDisposable>(x: T): T { disposableTracker?.trackDisposable(x); return x; } function markAsDisposed(disposable: IDisposable): void { disposableTracker?.markAsDisposed(disposable); } function setParentOfDisposable(child: IDisposable, parent: IDisposable | null): void { disposableTracker?.setParent(child, parent); } function setParentOfDisposables(children: IDisposable[], parent: IDisposable | null): void { if (!disposableTracker) { return; } for (const child of children) { disposableTracker.setParent(child, parent); } } /** * Indicates that the given object is a singleton which does not need to be disposed. */ export function markAsSingleton<T extends IDisposable>(singleton: T): T { disposableTracker?.markAsSingleton(singleton); return singleton; } // #endregion /** * An object that performs a cleanup operation when `.dispose()` is called. * * Some examples of how disposables are used: * * - An event listener that removes itself when `.dispose()` is called. * - A resource such as a file system watcher that cleans up the resource when `.dispose()` is called. * - The return value from registering a provider. When `.dispose()` is called, the provider is unregistered. */ export interface IDisposable { dispose(): void; } /** * Check if `thing` is {@link IDisposable disposable}. */ export function isDisposable<E extends object>(thing: E): thing is E & IDisposable { return typeof (<IDisposable>thing).dispose === 'function' && (<IDisposable>thing).dispose.length === 0; } /** * Disposes of the value(s) passed in. */ export function dispose<T extends IDisposable>(disposable: T): T; export function dispose<T extends IDisposable>(disposable: T | undefined): T | undefined; export function dispose<T extends IDisposable, A extends Iterable<T> = Iterable<T>>(disposables: A): A; export function dispose<T extends IDisposable>(disposables: Array<T>): Array<T>; export function dispose<T extends IDisposable>(disposables: ReadonlyArray<T>): ReadonlyArray<T>; export function dispose<T extends IDisposable>(arg: T | Iterable<T> | undefined): any { if (Iterable.is(arg)) { const errors: any[] = []; for (const d of arg) { if (d) { try { d.dispose(); } catch (e) { errors.push(e); } } } if (errors.length === 1) { throw errors[0]; } else if (errors.length > 1) { throw new AggregateError(errors, 'Encountered errors while disposing of store'); } return Array.isArray(arg) ? [] : arg; } else if (arg) { arg.dispose(); return arg; } } export function disposeIfDisposable<T extends IDisposable | object>(disposables: Array<T>): Array<T> { for (const d of disposables) { if (isDisposable(d)) { d.dispose(); } } return []; } /** * Combine multiple disposable values into a single {@link IDisposable}. */ export function combinedDisposable(...disposables: IDisposable[]): IDisposable { const parent = toDisposable(() => dispose(disposables)); setParentOfDisposables(disposables, parent); return parent; } /** * Turn a function that implements dispose into an {@link IDisposable}. */ export function toDisposable(fn: () => void): IDisposable { const self = trackDisposable({ dispose: once(() => { markAsDisposed(self); fn(); }) }); return self; } /** * Manages a collection of disposable values. * * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a * store that has already been disposed of. */ export class DisposableStore implements IDisposable { static DISABLE_DISPOSED_WARNING = false; private readonly _toDispose = new Set<IDisposable>(); private _isDisposed = false; constructor() { trackDisposable(this); } /** * Dispose of all registered disposables and mark this object as disposed. * * Any future disposables added to this object will be disposed of on `add`. */ public dispose(): void { if (this._isDisposed) { return; } markAsDisposed(this); this._isDisposed = true; this.clear(); } /** * @return `true` if this object has been disposed of. */ public get isDisposed(): boolean { return this._isDisposed; } /** * Dispose of all registered disposables but do not mark this object as disposed. */ public clear(): void { if (this._toDispose.size === 0) { return; } try { dispose(this._toDispose); } finally { this._toDispose.clear(); } } /** * Add a new {@link IDisposable disposable} to the collection. */ public add<T extends IDisposable>(o: T): T { if (!o) { return o; } if ((o as unknown as DisposableStore) === this) { throw new Error('Cannot register a disposable on itself!'); } setParentOfDisposable(o, this); if (this._isDisposed) { if (!DisposableStore.DISABLE_DISPOSED_WARNING) { console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack); } } else { this._toDispose.add(o); } return o; } } /** * Abstract base class for a {@link IDisposable disposable} object. * * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of. */ export abstract class Disposable implements IDisposable { /** * A disposable that does nothing when it is disposed of. * * TODO: This should not be a static property. */ static readonly None = Object.freeze<IDisposable>({ dispose() { } }); protected readonly _store = new DisposableStore(); constructor() { trackDisposable(this); setParentOfDisposable(this._store, this); } public dispose(): void { markAsDisposed(this); this._store.dispose(); } /** * Adds `o` to the collection of disposables managed by this object. */ protected _register<T extends IDisposable>(o: T): T { if ((o as unknown as Disposable) === this) { throw new Error('Cannot register a disposable on itself!'); } return this._store.add(o); } } /** * Manages the lifecycle of a disposable value that may be changed. * * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up. */ export class MutableDisposable<T extends IDisposable> implements IDisposable { private _value?: T; private _isDisposed = false; constructor() { trackDisposable(this); } get value(): T | undefined { return this._isDisposed ? undefined : this._value; } set value(value: T | undefined) { if (this._isDisposed || value === this._value) { return; } this._value?.dispose(); if (value) { setParentOfDisposable(value, this); } this._value = value; } /** * Resets the stored value and disposed of the previously stored value. */ clear(): void { this.value = undefined; } dispose(): void { this._isDisposed = true; markAsDisposed(this); this._value?.dispose(); this._value = undefined; } /** * Clears the value, but does not dispose it. * The old value is returned. */ clearAndLeak(): T | undefined { const oldValue = this._value; this._value = undefined; if (oldValue) { setParentOfDisposable(oldValue, null); } return oldValue; } } export class RefCountedDisposable { private _counter: number = 1; constructor( private readonly _disposable: IDisposable, ) { } acquire() { this._counter++; return this; } release() { if (--this._counter === 0) { this._disposable.dispose(); } return this; } } /** * A safe disposable can be `unset` so that a leaked reference (listener) * can be cut-off. */ export class SafeDisposable implements IDisposable { dispose: () => void = () => { }; unset: () => void = () => { }; isset: () => boolean = () => false; constructor() { trackDisposable(this); } set(fn: Function) { let callback: Function | undefined = fn; this.unset = () => callback = undefined; this.isset = () => callback !== undefined; this.dispose = () => { if (callback) { callback(); callback = undefined; markAsDisposed(this); } }; return this; } } export interface IReference<T> extends IDisposable { readonly object: T; } export abstract class ReferenceCollection<T> { private readonly references: Map<string, { readonly object: T; counter: number }> = new Map(); acquire(key: string, ...args: any[]): IReference<T> { let reference = this.references.get(key); if (!reference) { reference = { counter: 0, object: this.createReferencedObject(key, ...args) }; this.references.set(key, reference); } const { object } = reference; const dispose = once(() => { if (--reference!.counter === 0) { this.destroyReferencedObject(key, reference!.object); this.references.delete(key); } }); reference.counter++; return { object, dispose }; } protected abstract createReferencedObject(key: string, ...args: any[]): T; protected abstract destroyReferencedObject(key: string, object: T): void; } /** * Unwraps a reference collection of promised values. Makes sure * references are disposed whenever promises get rejected. */ export class AsyncReferenceCollection<T> { constructor(private referenceCollection: ReferenceCollection<Promise<T>>) { } async acquire(key: string, ...args: any[]): Promise<IReference<T>> { const ref = this.referenceCollection.acquire(key, ...args); try { const object = await ref.object; return { object, dispose: () => ref.dispose() }; } catch (error) { ref.dispose(); throw error; } } } export class ImmortalReference<T> implements IReference<T> { constructor(public object: T) { } dispose(): void { /* noop */ } } export function disposeOnReturn(fn: (store: DisposableStore) => void): void { const store = new DisposableStore(); try { fn(store); } finally { store.dispose(); } } /** * A map the manages the lifecycle of the values that it stores. */ export class DisposableMap<K, V extends IDisposable = IDisposable> implements IDisposable { private readonly _store = new Map<K, V>(); private _isDisposed = false; constructor() { trackDisposable(this); } /** * Disposes of all stored values and mark this object as disposed. * * Trying to use this object after it has been disposed of is an error. */ dispose(): void { markAsDisposed(this); this._isDisposed = true; this.clearAndDisposeAll(); } /** * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed. */ clearAndDisposeAll(): void { if (!this._store.size) { return; } try { dispose(this._store.values()); } finally { this._store.clear(); } } has(key: K): boolean { return this._store.has(key); } get(key: K): V | undefined { return this._store.get(key); } set(key: K, value: V, skipDisposeOnOverwrite = false): void { if (this._isDisposed) { console.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack); } if (!skipDisposeOnOverwrite) { this._store.get(key)?.dispose(); } this._store.set(key, value); } /** * Delete the value stored for `key` from this map and also dispose of it. */ deleteAndDispose(key: K): void { this._store.get(key)?.dispose(); this._store.delete(key); } [Symbol.iterator](): IterableIterator<[K, V]> { return this._store[Symbol.iterator](); } }
src/vs/base/common/lifecycle.ts
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.00017335791199002415, 0.00016878543829079717, 0.00015980505850166082, 0.00016906218661461025, 0.0000026135448933928274 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tinitData.environment.extensionTestsLocationURI = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTestsLocationURI));\n", "\t\tinitData.environment.globalStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.globalStorageHome));\n", "\t\tinitData.environment.workspaceStorageHome = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.workspaceStorageHome));\n", "\t\tinitData.nlsBaseUrl = URI.revive(rpcProtocol.transformIncomingURIs(initData.nlsBaseUrl));\n", "\t\tinitData.logsLocation = URI.revive(rpcProtocol.transformIncomingURIs(initData.logsLocation));\n", "\t\tinitData.logFile = URI.revive(rpcProtocol.transformIncomingURIs(initData.logFile));\n", "\t\tinitData.workspace = rpcProtocol.transformIncomingURIs(initData.workspace);\n", "\t\treturn initData;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinitData.environment.extensionTelemetryLogResource = URI.revive(rpcProtocol.transformIncomingURIs(initData.environment.extensionTelemetryLogResource));\n" ], "file_path": "src/vs/workbench/api/common/extensionHostMain.ts", "type": "add", "edit_start_line_idx": 180 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Connection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder, TextDocumentSyncKind, NotificationType, Disposable, TextDocumentIdentifier, Range, FormattingOptions, TextEdit, Diagnostic } from 'vscode-languageserver'; import { URI } from 'vscode-uri'; import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet, TextDocument, Position } from 'vscode-css-languageservice'; import { getLanguageModelCache } from './languageModelCache'; import { runSafeAsync } from './utils/runner'; import { DiagnosticsSupport, registerDiagnosticsPullSupport, registerDiagnosticsPushSupport } from './utils/validation'; import { getDocumentContext } from './utils/documentContext'; import { fetchDataProviders } from './customData'; import { RequestService, getRequestService } from './requests'; namespace CustomDataChangedNotification { export const type: NotificationType<string[]> = new NotificationType('css/customDataChanged'); } export interface Settings { css: LanguageSettings; less: LanguageSettings; scss: LanguageSettings; } export interface RuntimeEnvironment { readonly file?: RequestService; readonly http?: RequestService; readonly timer: { setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable; setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable; }; } export function startServer(connection: Connection, runtime: RuntimeEnvironment) { // Create a text document manager. const documents = new TextDocuments(TextDocument); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document)); documents.onDidClose(e => { stylesheets.onDocumentRemoved(e.document); }); connection.onShutdown(() => { stylesheets.dispose(); }); let scopedSettingsSupport = false; let foldingRangeLimit = Number.MAX_VALUE; let workspaceFolders: WorkspaceFolder[]; let formatterMaxNumberOfEdits = Number.MAX_VALUE; let dataProvidersReady: Promise<any> = Promise.resolve(); let diagnosticsSupport: DiagnosticsSupport | undefined; const languageServices: { [id: string]: LanguageService } = {}; const notReady = () => Promise.reject('Not Ready'); let requestService: RequestService = { getContent: notReady, stat: notReady, readDirectory: notReady }; // After the server has started the client sends an initialize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilities. connection.onInitialize((params: InitializeParams): InitializeResult => { const initializationOptions = params.initializationOptions as any || {}; workspaceFolders = (<any>params).workspaceFolders; if (!Array.isArray(workspaceFolders)) { workspaceFolders = []; if (params.rootPath) { workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString(true) }); } } requestService = getRequestService(initializationOptions?.handledSchemas || ['file'], connection, runtime); function getClientCapability<T>(name: string, def: T) { const keys = name.split('.'); let c: any = params.capabilities; for (let i = 0; c && i < keys.length; i++) { if (!c.hasOwnProperty(keys[i])) { return def; } c = c[keys[i]]; } return c; } const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false); scopedSettingsSupport = !!getClientCapability('workspace.configuration', false); foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE); formatterMaxNumberOfEdits = initializationOptions?.customCapabilities?.rangeFormatting?.editLimit || Number.MAX_VALUE; languageServices.css = getCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities }); languageServices.scss = getSCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities }); languageServices.less = getLESSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities }); const supportsDiagnosticPull = getClientCapability('textDocument.diagnostic', undefined); if (supportsDiagnosticPull === undefined) { diagnosticsSupport = registerDiagnosticsPushSupport(documents, connection, runtime, validateTextDocument); } else { diagnosticsSupport = registerDiagnosticsPullSupport(documents, connection, runtime, validateTextDocument); } const capabilities: ServerCapabilities = { textDocumentSync: TextDocumentSyncKind.Incremental, completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/', '-', ':'] } : undefined, hoverProvider: true, documentSymbolProvider: true, referencesProvider: true, definitionProvider: true, documentHighlightProvider: true, documentLinkProvider: { resolveProvider: false }, codeActionProvider: true, renameProvider: true, colorProvider: {}, foldingRangeProvider: true, selectionRangeProvider: true, diagnosticProvider: { documentSelector: null, interFileDependencies: false, workspaceDiagnostics: false }, documentRangeFormattingProvider: initializationOptions?.provideFormatter === true, documentFormattingProvider: initializationOptions?.provideFormatter === true, }; return { capabilities }; }); function getLanguageService(document: TextDocument) { let service = languageServices[document.languageId]; if (!service) { connection.console.log('Document type is ' + document.languageId + ', using css instead.'); service = languageServices['css']; } return service; } let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {}; // remove document settings on close documents.onDidClose(e => { delete documentSettings[e.document.uri]; }); function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> { if (scopedSettingsSupport) { let promise = documentSettings[textDocument.uri]; if (!promise) { const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] }; promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0] as LanguageSettings | undefined); documentSettings[textDocument.uri] = promise; } return promise; } return Promise.resolve(undefined); } // The settings have changed. Is send on server activation as well. connection.onDidChangeConfiguration(change => { updateConfiguration(change.settings as any); }); function updateConfiguration(settings: any) { for (const languageId in languageServices) { languageServices[languageId].configure(settings[languageId]); } // reset all document settings documentSettings = {}; diagnosticsSupport?.requestRefresh(); } async function validateTextDocument(textDocument: TextDocument): Promise<Diagnostic[]> { const settingsPromise = getDocumentSettings(textDocument); const [settings] = await Promise.all([settingsPromise, dataProvidersReady]); const stylesheet = stylesheets.get(textDocument); return getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings); } function updateDataProviders(dataPaths: string[]) { dataProvidersReady = fetchDataProviders(dataPaths, requestService).then(customDataProviders => { for (const lang in languageServices) { languageServices[lang].setDataProviders(true, customDataProviders); } }); } connection.onCompletion((textDocumentPosition, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(textDocumentPosition.textDocument.uri); if (document) { const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]); const styleSheet = stylesheets.get(document); const documentContext = getDocumentContext(document.uri, workspaceFolders); return getLanguageService(document).doComplete2(document, textDocumentPosition.position, styleSheet, documentContext, settings?.completion); } return null; }, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token); }); connection.onHover((textDocumentPosition, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(textDocumentPosition.textDocument.uri); if (document) { const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]); const styleSheet = stylesheets.get(document); return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet, settings?.hover); } return null; }, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token); }); connection.onDocumentSymbol((documentSymbolParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentSymbolParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentSymbols2(document, stylesheet); } return []; }, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token); }); connection.onDefinition((documentDefinitionParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentDefinitionParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet); } return null; }, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token); }); connection.onDocumentHighlight((documentHighlightParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentHighlightParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet); } return []; }, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token); }); connection.onDocumentLinks(async (documentLinkParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentLinkParams.textDocument.uri); if (document) { await dataProvidersReady; const documentContext = getDocumentContext(document.uri, workspaceFolders); const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext); } return []; }, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token); }); connection.onReferences((referenceParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(referenceParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet); } return []; }, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token); }); connection.onCodeAction((codeActionParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(codeActionParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet); } return []; }, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token); }); connection.onDocumentColor((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentColors(document, stylesheet); } return []; }, [], `Error while computing document colors for ${params.textDocument.uri}`, token); }); connection.onColorPresentation((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range); } return []; }, [], `Error while computing color presentations for ${params.textDocument.uri}`, token); }); connection.onRenameRequest((renameParameters, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(renameParameters.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet); } return null; }, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token); }); connection.onFoldingRanges((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { await dataProvidersReady; return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit }); } return null; }, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token); }); connection.onSelectionRanges((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); const positions: Position[] = params.positions; if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).getSelectionRanges(document, positions, stylesheet); } return []; }, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token); }); async function onFormat(textDocument: TextDocumentIdentifier, range: Range | undefined, options: FormattingOptions): Promise<TextEdit[]> { const document = documents.get(textDocument.uri); if (document) { const edits = getLanguageService(document).format(document, range ?? getFullRange(document), options); if (edits.length > formatterMaxNumberOfEdits) { const newText = TextDocument.applyEdits(document, edits); return [TextEdit.replace(getFullRange(document), newText)]; } return edits; } return []; } connection.onDocumentRangeFormatting((formatParams, token) => { return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, formatParams.range, formatParams.options), [], `Error while formatting range for ${formatParams.textDocument.uri}`, token); }); connection.onDocumentFormatting((formatParams, token) => { return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, undefined, formatParams.options), [], `Error while formatting ${formatParams.textDocument.uri}`, token); }); connection.onNotification(CustomDataChangedNotification.type, updateDataProviders); // Listen on the connection connection.listen(); } function getFullRange(document: TextDocument): Range { return Range.create(Position.create(0, 0), document.positionAt(document.getText().length)); }
extensions/css-language-features/server/src/cssServer.ts
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.0005839421064592898, 0.0001820373727241531, 0.0001639525144128129, 0.000171920022694394, 0.00006524968193843961 ]
{ "id": 1, "code_window": [ "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\tprivate extensionHostDebugEnvironment: IExtensionHostDebugEnvironment | undefined = undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/browser/environmentService.ts", "type": "replace", "edit_start_line_idx": 133 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Schemas } from 'vs/base/common/network'; import { joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ExtensionKind, IEnvironmentService, IExtensionHostDebugParams } from 'vs/platform/environment/common/environment'; import { IPath } from 'vs/platform/window/common/window'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IWorkbenchConstructionOptions } from 'vs/workbench/browser/web.api'; import { IProductService } from 'vs/platform/product/common/productService'; import { memoize } from 'vs/base/common/decorators'; import { onUnexpectedError } from 'vs/base/common/errors'; import { parseLineAndColumnAware } from 'vs/base/common/extpath'; import { LogLevelToString } from 'vs/platform/log/common/log'; import { isUndefined } from 'vs/base/common/types'; import { refineServiceDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { EXTENSION_IDENTIFIER_WITH_LOG_REGEX } from 'vs/platform/environment/common/environmentService'; export const IBrowserWorkbenchEnvironmentService = refineServiceDecorator<IEnvironmentService, IBrowserWorkbenchEnvironmentService>(IEnvironmentService); /** * A subclass of the `IWorkbenchEnvironmentService` to be used only environments * where the web API is available (browsers, Electron). */ export interface IBrowserWorkbenchEnvironmentService extends IWorkbenchEnvironmentService { /** * Options used to configure the workbench. */ readonly options?: IWorkbenchConstructionOptions; } export class BrowserWorkbenchEnvironmentService implements IBrowserWorkbenchEnvironmentService { declare readonly _serviceBrand: undefined; @memoize get remoteAuthority(): string | undefined { return this.options.remoteAuthority; } @memoize get isBuilt(): boolean { return !!this.productService.commit; } @memoize get logsPath(): string { return this.logsHome.path; } @memoize get logLevel(): string | undefined { const logLevelFromPayload = this.payload?.get('logLevel'); if (logLevelFromPayload) { return logLevelFromPayload.split(',').find(entry => !EXTENSION_IDENTIFIER_WITH_LOG_REGEX.test(entry)); } return this.options.developmentOptions?.logLevel !== undefined ? LogLevelToString(this.options.developmentOptions?.logLevel) : undefined; } get extensionLogLevel(): [string, string][] | undefined { const logLevelFromPayload = this.payload?.get('logLevel'); if (logLevelFromPayload) { const result: [string, string][] = []; for (const entry of logLevelFromPayload.split(',')) { const matches = EXTENSION_IDENTIFIER_WITH_LOG_REGEX.exec(entry); if (matches && matches[1] && matches[2]) { result.push([matches[1], matches[2]]); } } return result.length ? result : undefined; } return this.options.developmentOptions?.extensionLogLevel !== undefined ? this.options.developmentOptions?.extensionLogLevel.map(([extension, logLevel]) => ([extension, LogLevelToString(logLevel)])) : undefined; } @memoize get windowLogsPath(): URI { return this.logsHome; } @memoize get logFile(): URI { return joinPath(this.windowLogsPath, 'window.log'); } @memoize get userRoamingDataHome(): URI { return URI.file('/User').with({ scheme: Schemas.vscodeUserData }); } @memoize get argvResource(): URI { return joinPath(this.userRoamingDataHome, 'argv.json'); } @memoize get cacheHome(): URI { return joinPath(this.userRoamingDataHome, 'caches'); } @memoize get workspaceStorageHome(): URI { return joinPath(this.userRoamingDataHome, 'workspaceStorage'); } @memoize get localHistoryHome(): URI { return joinPath(this.userRoamingDataHome, 'History'); } @memoize get stateResource(): URI { return joinPath(this.userRoamingDataHome, 'State', 'storage.json'); } /** * In Web every workspace can potentially have scoped user-data * and/or extensions and if Sync state is shared then it can make * Sync error prone - say removing extensions from another workspace. * Hence scope Sync state per workspace. Sync scoped to a workspace * is capable of handling opening same workspace in multiple windows. */ @memoize get userDataSyncHome(): URI { return joinPath(this.userRoamingDataHome, 'sync', this.workspaceId); } @memoize get userDataSyncLogResource(): URI { return joinPath(this.logsHome, 'userDataSync.log'); } @memoize get editSessionsLogResource(): URI { return joinPath(this.logsHome, 'editSessions.log'); } @memoize get remoteTunnelLogResource(): URI { return joinPath(this.logsHome, 'remoteTunnel.log'); } @memoize get sync(): 'on' | 'off' | undefined { return undefined; } @memoize get keyboardLayoutResource(): URI { return joinPath(this.userRoamingDataHome, 'keyboardLayout.json'); } @memoize get untitledWorkspacesHome(): URI { return joinPath(this.userRoamingDataHome, 'Workspaces'); } @memoize get serviceMachineIdResource(): URI { return joinPath(this.userRoamingDataHome, 'machineid'); } @memoize get extHostLogsPath(): URI { return joinPath(this.logsHome, 'exthost'); } @memoize get extHostTelemetryLogFile(): URI { return joinPath(this.extHostLogsPath, 'telemetry.log'); } private extensionHostDebugEnvironment: IExtensionHostDebugEnvironment | undefined = undefined; @memoize get debugExtensionHost(): IExtensionHostDebugParams { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.params; } @memoize get isExtensionDevelopment(): boolean { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.isExtensionDevelopment; } @memoize get extensionDevelopmentLocationURI(): URI[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionDevelopmentLocationURI; } @memoize get extensionDevelopmentLocationKind(): ExtensionKind[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionDevelopmentKind; } @memoize get extensionTestsLocationURI(): URI | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionTestsLocationURI; } @memoize get extensionEnabledProposedApi(): string[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionEnabledProposedApi; } @memoize get debugRenderer(): boolean { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.debugRenderer; } @memoize get enableSmokeTestDriver() { return this.options.developmentOptions?.enableSmokeTestDriver; } @memoize get disableExtensions() { return this.payload?.get('disableExtensions') === 'true'; } @memoize get enableExtensions() { return this.options.enabledExtensions; } @memoize get webviewExternalEndpoint(): string { const endpoint = this.options.webviewEndpoint || this.productService.webviewContentExternalBaseUrlTemplate || 'https://{{uuid}}.vscode-cdn.net/{{quality}}/{{commit}}/out/vs/workbench/contrib/webview/browser/pre/'; const webviewExternalEndpointCommit = this.payload?.get('webviewExternalEndpointCommit'); return endpoint .replace('{{commit}}', webviewExternalEndpointCommit ?? this.productService.commit ?? 'ef65ac1ba57f57f2a3961bfe94aa20481caca4c6') .replace('{{quality}}', (webviewExternalEndpointCommit ? 'insider' : this.productService.quality) ?? 'insider'); } @memoize get telemetryLogResource(): URI { return joinPath(this.logsHome, 'telemetry.log'); } get extensionTelemetryLogResource(): URI { return joinPath(this.logsHome, 'extensionTelemetry.log'); } @memoize get disableTelemetry(): boolean { return false; } @memoize get verbose(): boolean { return this.payload?.get('verbose') === 'true'; } @memoize get logExtensionHostCommunication(): boolean { return this.payload?.get('logExtensionHostCommunication') === 'true'; } @memoize get skipReleaseNotes(): boolean { return this.payload?.get('skipReleaseNotes') === 'true'; } @memoize get skipWelcome(): boolean { return this.payload?.get('skipWelcome') === 'true'; } @memoize get disableWorkspaceTrust(): boolean { return !this.options.enableWorkspaceTrust; } @memoize get lastActiveProfile(): string | undefined { return this.payload?.get('lastActiveProfile'); } editSessionId: string | undefined = this.options.editSessionId; private payload: Map<string, string> | undefined; constructor( private readonly workspaceId: string, private readonly logsHome: URI, readonly options: IWorkbenchConstructionOptions, private readonly productService: IProductService ) { if (options.workspaceProvider && Array.isArray(options.workspaceProvider.payload)) { try { this.payload = new Map(options.workspaceProvider.payload); } catch (error) { onUnexpectedError(error); // possible invalid payload for map } } } private resolveExtensionHostDebugEnvironment(): IExtensionHostDebugEnvironment { const extensionHostDebugEnvironment: IExtensionHostDebugEnvironment = { params: { port: null, break: false }, debugRenderer: false, isExtensionDevelopment: false, extensionDevelopmentLocationURI: undefined, extensionDevelopmentKind: undefined }; // Fill in selected extra environmental properties if (this.payload) { for (const [key, value] of this.payload) { switch (key) { case 'extensionDevelopmentPath': if (!extensionHostDebugEnvironment.extensionDevelopmentLocationURI) { extensionHostDebugEnvironment.extensionDevelopmentLocationURI = []; } extensionHostDebugEnvironment.extensionDevelopmentLocationURI.push(URI.parse(value)); extensionHostDebugEnvironment.isExtensionDevelopment = true; break; case 'extensionDevelopmentKind': extensionHostDebugEnvironment.extensionDevelopmentKind = [<ExtensionKind>value]; break; case 'extensionTestsPath': extensionHostDebugEnvironment.extensionTestsLocationURI = URI.parse(value); break; case 'debugRenderer': extensionHostDebugEnvironment.debugRenderer = value === 'true'; break; case 'debugId': extensionHostDebugEnvironment.params.debugId = value; break; case 'inspect-brk-extensions': extensionHostDebugEnvironment.params.port = parseInt(value); extensionHostDebugEnvironment.params.break = true; break; case 'inspect-extensions': extensionHostDebugEnvironment.params.port = parseInt(value); break; case 'enableProposedApi': extensionHostDebugEnvironment.extensionEnabledProposedApi = []; break; } } } const developmentOptions = this.options.developmentOptions; if (developmentOptions && !extensionHostDebugEnvironment.isExtensionDevelopment) { if (developmentOptions.extensions?.length) { extensionHostDebugEnvironment.extensionDevelopmentLocationURI = developmentOptions.extensions.map(e => URI.revive(e)); extensionHostDebugEnvironment.isExtensionDevelopment = true; } if (developmentOptions.extensionTestsPath) { extensionHostDebugEnvironment.extensionTestsLocationURI = URI.revive(developmentOptions.extensionTestsPath); } } return extensionHostDebugEnvironment; } @memoize get filesToOpenOrCreate(): IPath<ITextEditorOptions>[] | undefined { if (this.payload) { const fileToOpen = this.payload.get('openFile'); if (fileToOpen) { const fileUri = URI.parse(fileToOpen); // Support: --goto parameter to open on line/col if (this.payload.has('gotoLineMode')) { const pathColumnAware = parseLineAndColumnAware(fileUri.path); return [{ fileUri: fileUri.with({ path: pathColumnAware.path }), options: { selection: !isUndefined(pathColumnAware.line) ? { startLineNumber: pathColumnAware.line, startColumn: pathColumnAware.column || 1 } : undefined } }]; } return [{ fileUri }]; } } return undefined; } @memoize get filesToDiff(): IPath[] | undefined { if (this.payload) { const fileToDiffPrimary = this.payload.get('diffFilePrimary'); const fileToDiffSecondary = this.payload.get('diffFileSecondary'); if (fileToDiffPrimary && fileToDiffSecondary) { return [ { fileUri: URI.parse(fileToDiffSecondary) }, { fileUri: URI.parse(fileToDiffPrimary) } ]; } } return undefined; } @memoize get filesToMerge(): IPath[] | undefined { if (this.payload) { const fileToMerge1 = this.payload.get('mergeFile1'); const fileToMerge2 = this.payload.get('mergeFile2'); const fileToMergeBase = this.payload.get('mergeFileBase'); const fileToMergeResult = this.payload.get('mergeFileResult'); if (fileToMerge1 && fileToMerge2 && fileToMergeBase && fileToMergeResult) { return [ { fileUri: URI.parse(fileToMerge1) }, { fileUri: URI.parse(fileToMerge2) }, { fileUri: URI.parse(fileToMergeBase) }, { fileUri: URI.parse(fileToMergeResult) } ]; } } return undefined; } } interface IExtensionHostDebugEnvironment { params: IExtensionHostDebugParams; debugRenderer: boolean; isExtensionDevelopment: boolean; extensionDevelopmentLocationURI?: URI[]; extensionDevelopmentKind?: ExtensionKind[]; extensionTestsLocationURI?: URI; extensionEnabledProposedApi?: string[]; }
src/vs/workbench/services/environment/browser/environmentService.ts
1
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.9992297887802124, 0.3175809681415558, 0.00016465877706650645, 0.00028003656188957393, 0.4638427495956421 ]
{ "id": 1, "code_window": [ "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\tprivate extensionHostDebugEnvironment: IExtensionHostDebugEnvironment | undefined = undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/browser/environmentService.ts", "type": "replace", "edit_start_line_idx": 133 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-hover { cursor: default; position: absolute; overflow: hidden; z-index: 50; user-select: text; -webkit-user-select: text; box-sizing: initial; animation: fadein 100ms linear; line-height: 1.5em; } .monaco-hover.hidden { display: none; } .monaco-hover a:hover { cursor: pointer; } .monaco-hover .hover-contents:not(.html-hover-contents) { padding: 4px 8px; } .monaco-hover .markdown-hover > .hover-contents:not(.code-hover-contents) { max-width: 500px; word-wrap: break-word; } .monaco-hover .markdown-hover > .hover-contents:not(.code-hover-contents) hr { min-width: 100%; } .monaco-hover p, .monaco-hover .code, .monaco-hover ul { margin: 8px 0; } .monaco-hover code { font-family: var(--monaco-monospace-font); } .monaco-hover hr { box-sizing: border-box; border-left: 0px; border-right: 0px; margin-top: 4px; margin-bottom: -4px; margin-left: -8px; margin-right: -8px; height: 1px; } .monaco-hover p:first-child, .monaco-hover .code:first-child, .monaco-hover ul:first-child { margin-top: 0; } .monaco-hover p:last-child, .monaco-hover .code:last-child, .monaco-hover ul:last-child { margin-bottom: 0; } /* MarkupContent Layout */ .monaco-hover ul { padding-left: 20px; } .monaco-hover ol { padding-left: 20px; } .monaco-hover li > p { margin-bottom: 0; } .monaco-hover li > ul { margin-top: 0; } .monaco-hover code { border-radius: 3px; padding: 0 0.4em; } .monaco-hover .monaco-tokenized-source { white-space: pre-wrap; } .monaco-hover .hover-row.status-bar { font-size: 12px; line-height: 22px; } .monaco-hover .hover-row.status-bar .actions { display: flex; padding: 0px 8px; } .monaco-hover .hover-row.status-bar .actions .action-container { margin-right: 16px; cursor: pointer; } .monaco-hover .hover-row.status-bar .actions .action-container .action .icon { padding-right: 4px; } .monaco-hover .markdown-hover .hover-contents .codicon { color: inherit; font-size: inherit; vertical-align: middle; } .monaco-hover .hover-contents a.code-link:hover, .monaco-hover .hover-contents a.code-link { color: inherit; } .monaco-hover .hover-contents a.code-link:before { content: '('; } .monaco-hover .hover-contents a.code-link:after { content: ')'; } .monaco-hover .hover-contents a.code-link > span { text-decoration: underline; /** Hack to force underline to show **/ border-bottom: 1px solid transparent; text-underline-position: under; } /** Spans in markdown hovers need a margin-bottom to avoid looking cramped: https://github.com/microsoft/vscode/issues/101496 **/ .monaco-hover .markdown-hover .hover-contents:not(.code-hover-contents):not(.html-hover-contents) span { margin-bottom: 4px; display: inline-block; } .monaco-hover-content .action-container a { -webkit-user-select: none; user-select: none; } .monaco-hover-content .action-container.disabled { pointer-events: none; opacity: 0.4; cursor: default; }
src/vs/base/browser/ui/hover/hover.css
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.00017785515228752047, 0.00017244636546820402, 0.0001669575140113011, 0.00017295408179052174, 0.000002857162598957075 ]
{ "id": 1, "code_window": [ "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\tprivate extensionHostDebugEnvironment: IExtensionHostDebugEnvironment | undefined = undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/browser/environmentService.ts", "type": "replace", "edit_start_line_idx": 133 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // THIS IS A GENERATED FILE. DO NOT EDIT DIRECTLY. export const allApiProposals = Object.freeze({ authSession: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.authSession.d.ts', commentsResolvedState: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.commentsResolvedState.d.ts', contribCommentPeekContext: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribCommentPeekContext.d.ts', contribEditSessions: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribEditSessions.d.ts', contribEditorContentMenu: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribEditorContentMenu.d.ts', contribLabelFormatterWorkspaceTooltip: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribLabelFormatterWorkspaceTooltip.d.ts', contribMenuBarHome: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMenuBarHome.d.ts', contribMergeEditorMenus: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribMergeEditorMenus.d.ts', contribNotebookStaticPreloads: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribNotebookStaticPreloads.d.ts', contribRemoteHelp: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribRemoteHelp.d.ts', contribShareMenu: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribShareMenu.d.ts', contribTerminalQuickFixes: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribTerminalQuickFixes.d.ts', contribViewsRemote: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewsRemote.d.ts', contribViewsWelcome: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.contribViewsWelcome.d.ts', customEditorMove: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.customEditorMove.d.ts', diffCommand: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.diffCommand.d.ts', diffContentOptions: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.diffContentOptions.d.ts', documentFiltersExclusive: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.documentFiltersExclusive.d.ts', documentPaste: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.documentPaste.d.ts', editSessionIdentityProvider: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editSessionIdentityProvider.d.ts', editorInsets: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.editorInsets.d.ts', envShellEvent: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.envShellEvent.d.ts', extensionLog: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionLog.d.ts', extensionRuntime: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionRuntime.d.ts', extensionsAny: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.extensionsAny.d.ts', externalUriOpener: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.externalUriOpener.d.ts', fileSearchProvider: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileSearchProvider.d.ts', findTextInFiles: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findTextInFiles.d.ts', fsChunks: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fsChunks.d.ts', idToken: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.idToken.d.ts', inlineCompletionsAdditions: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.inlineCompletionsAdditions.d.ts', inlineCompletionsNew: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.inlineCompletionsNew.d.ts', interactiveWindow: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.interactiveWindow.d.ts', ipc: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.ipc.d.ts', notebookCellExecutionState: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookCellExecutionState.d.ts', notebookContentProvider: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookContentProvider.d.ts', notebookControllerAffinityHidden: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookControllerAffinityHidden.d.ts', notebookControllerKind: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookControllerKind.d.ts', notebookDeprecated: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookDeprecated.d.ts', notebookEditor: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookEditor.d.ts', notebookKernelSource: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookKernelSource.d.ts', notebookLiveShare: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookLiveShare.d.ts', notebookMessaging: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookMessaging.d.ts', notebookMime: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.notebookMime.d.ts', portsAttributes: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.portsAttributes.d.ts', quickPickSortByLabel: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.quickPickSortByLabel.d.ts', resolvers: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.resolvers.d.ts', scmActionButton: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmActionButton.d.ts', scmSelectedProvider: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmSelectedProvider.d.ts', scmValidation: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.scmValidation.d.ts', tabInputTextMerge: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tabInputTextMerge.d.ts', taskPresentationGroup: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.taskPresentationGroup.d.ts', telemetry: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.telemetry.d.ts', telemetryLogger: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.telemetryLogger.d.ts', terminalDataWriteEvent: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalDataWriteEvent.d.ts', terminalDimensions: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalDimensions.d.ts', testCoverage: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.testCoverage.d.ts', testObserver: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.testObserver.d.ts', textSearchProvider: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchProvider.d.ts', timeline: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.timeline.d.ts', tokenInformation: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tokenInformation.d.ts', treeItemCheckbox: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeItemCheckbox.d.ts', treeViewReveal: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.treeViewReveal.d.ts', tunnels: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.tunnels.d.ts', workspaceTrust: 'https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.workspaceTrust.d.ts' }); export type ApiProposalName = keyof typeof allApiProposals;
src/vs/workbench/services/extensions/common/extensionsApiProposals.ts
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.00021883443696424365, 0.0001756696728989482, 0.0001665833406150341, 0.0001693724188953638, 0.000016467043678858317 ]
{ "id": 1, "code_window": [ "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\tprivate extensionHostDebugEnvironment: IExtensionHostDebugEnvironment | undefined = undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/browser/environmentService.ts", "type": "replace", "edit_start_line_idx": 133 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/yaml/yarn.lock
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.00016968930140137672, 0.00016968930140137672, 0.00016968930140137672, 0.00016968930140137672, 0 ]
{ "id": 2, "code_window": [ "\tget extHostLogsPath(): URI { return joinPath(this.windowLogsPath, 'exthost'); }\n", "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\t@memoize\n", "\tget webviewExternalEndpoint(): string { return `${Schemas.vscodeWebview}://{{uuid}}`; }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/electron-sandbox/environmentService.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Schemas } from 'vs/base/common/network'; import { joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ExtensionKind, IEnvironmentService, IExtensionHostDebugParams } from 'vs/platform/environment/common/environment'; import { IPath } from 'vs/platform/window/common/window'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IWorkbenchConstructionOptions } from 'vs/workbench/browser/web.api'; import { IProductService } from 'vs/platform/product/common/productService'; import { memoize } from 'vs/base/common/decorators'; import { onUnexpectedError } from 'vs/base/common/errors'; import { parseLineAndColumnAware } from 'vs/base/common/extpath'; import { LogLevelToString } from 'vs/platform/log/common/log'; import { isUndefined } from 'vs/base/common/types'; import { refineServiceDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { EXTENSION_IDENTIFIER_WITH_LOG_REGEX } from 'vs/platform/environment/common/environmentService'; export const IBrowserWorkbenchEnvironmentService = refineServiceDecorator<IEnvironmentService, IBrowserWorkbenchEnvironmentService>(IEnvironmentService); /** * A subclass of the `IWorkbenchEnvironmentService` to be used only environments * where the web API is available (browsers, Electron). */ export interface IBrowserWorkbenchEnvironmentService extends IWorkbenchEnvironmentService { /** * Options used to configure the workbench. */ readonly options?: IWorkbenchConstructionOptions; } export class BrowserWorkbenchEnvironmentService implements IBrowserWorkbenchEnvironmentService { declare readonly _serviceBrand: undefined; @memoize get remoteAuthority(): string | undefined { return this.options.remoteAuthority; } @memoize get isBuilt(): boolean { return !!this.productService.commit; } @memoize get logsPath(): string { return this.logsHome.path; } @memoize get logLevel(): string | undefined { const logLevelFromPayload = this.payload?.get('logLevel'); if (logLevelFromPayload) { return logLevelFromPayload.split(',').find(entry => !EXTENSION_IDENTIFIER_WITH_LOG_REGEX.test(entry)); } return this.options.developmentOptions?.logLevel !== undefined ? LogLevelToString(this.options.developmentOptions?.logLevel) : undefined; } get extensionLogLevel(): [string, string][] | undefined { const logLevelFromPayload = this.payload?.get('logLevel'); if (logLevelFromPayload) { const result: [string, string][] = []; for (const entry of logLevelFromPayload.split(',')) { const matches = EXTENSION_IDENTIFIER_WITH_LOG_REGEX.exec(entry); if (matches && matches[1] && matches[2]) { result.push([matches[1], matches[2]]); } } return result.length ? result : undefined; } return this.options.developmentOptions?.extensionLogLevel !== undefined ? this.options.developmentOptions?.extensionLogLevel.map(([extension, logLevel]) => ([extension, LogLevelToString(logLevel)])) : undefined; } @memoize get windowLogsPath(): URI { return this.logsHome; } @memoize get logFile(): URI { return joinPath(this.windowLogsPath, 'window.log'); } @memoize get userRoamingDataHome(): URI { return URI.file('/User').with({ scheme: Schemas.vscodeUserData }); } @memoize get argvResource(): URI { return joinPath(this.userRoamingDataHome, 'argv.json'); } @memoize get cacheHome(): URI { return joinPath(this.userRoamingDataHome, 'caches'); } @memoize get workspaceStorageHome(): URI { return joinPath(this.userRoamingDataHome, 'workspaceStorage'); } @memoize get localHistoryHome(): URI { return joinPath(this.userRoamingDataHome, 'History'); } @memoize get stateResource(): URI { return joinPath(this.userRoamingDataHome, 'State', 'storage.json'); } /** * In Web every workspace can potentially have scoped user-data * and/or extensions and if Sync state is shared then it can make * Sync error prone - say removing extensions from another workspace. * Hence scope Sync state per workspace. Sync scoped to a workspace * is capable of handling opening same workspace in multiple windows. */ @memoize get userDataSyncHome(): URI { return joinPath(this.userRoamingDataHome, 'sync', this.workspaceId); } @memoize get userDataSyncLogResource(): URI { return joinPath(this.logsHome, 'userDataSync.log'); } @memoize get editSessionsLogResource(): URI { return joinPath(this.logsHome, 'editSessions.log'); } @memoize get remoteTunnelLogResource(): URI { return joinPath(this.logsHome, 'remoteTunnel.log'); } @memoize get sync(): 'on' | 'off' | undefined { return undefined; } @memoize get keyboardLayoutResource(): URI { return joinPath(this.userRoamingDataHome, 'keyboardLayout.json'); } @memoize get untitledWorkspacesHome(): URI { return joinPath(this.userRoamingDataHome, 'Workspaces'); } @memoize get serviceMachineIdResource(): URI { return joinPath(this.userRoamingDataHome, 'machineid'); } @memoize get extHostLogsPath(): URI { return joinPath(this.logsHome, 'exthost'); } @memoize get extHostTelemetryLogFile(): URI { return joinPath(this.extHostLogsPath, 'telemetry.log'); } private extensionHostDebugEnvironment: IExtensionHostDebugEnvironment | undefined = undefined; @memoize get debugExtensionHost(): IExtensionHostDebugParams { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.params; } @memoize get isExtensionDevelopment(): boolean { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.isExtensionDevelopment; } @memoize get extensionDevelopmentLocationURI(): URI[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionDevelopmentLocationURI; } @memoize get extensionDevelopmentLocationKind(): ExtensionKind[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionDevelopmentKind; } @memoize get extensionTestsLocationURI(): URI | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionTestsLocationURI; } @memoize get extensionEnabledProposedApi(): string[] | undefined { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.extensionEnabledProposedApi; } @memoize get debugRenderer(): boolean { if (!this.extensionHostDebugEnvironment) { this.extensionHostDebugEnvironment = this.resolveExtensionHostDebugEnvironment(); } return this.extensionHostDebugEnvironment.debugRenderer; } @memoize get enableSmokeTestDriver() { return this.options.developmentOptions?.enableSmokeTestDriver; } @memoize get disableExtensions() { return this.payload?.get('disableExtensions') === 'true'; } @memoize get enableExtensions() { return this.options.enabledExtensions; } @memoize get webviewExternalEndpoint(): string { const endpoint = this.options.webviewEndpoint || this.productService.webviewContentExternalBaseUrlTemplate || 'https://{{uuid}}.vscode-cdn.net/{{quality}}/{{commit}}/out/vs/workbench/contrib/webview/browser/pre/'; const webviewExternalEndpointCommit = this.payload?.get('webviewExternalEndpointCommit'); return endpoint .replace('{{commit}}', webviewExternalEndpointCommit ?? this.productService.commit ?? 'ef65ac1ba57f57f2a3961bfe94aa20481caca4c6') .replace('{{quality}}', (webviewExternalEndpointCommit ? 'insider' : this.productService.quality) ?? 'insider'); } @memoize get telemetryLogResource(): URI { return joinPath(this.logsHome, 'telemetry.log'); } get extensionTelemetryLogResource(): URI { return joinPath(this.logsHome, 'extensionTelemetry.log'); } @memoize get disableTelemetry(): boolean { return false; } @memoize get verbose(): boolean { return this.payload?.get('verbose') === 'true'; } @memoize get logExtensionHostCommunication(): boolean { return this.payload?.get('logExtensionHostCommunication') === 'true'; } @memoize get skipReleaseNotes(): boolean { return this.payload?.get('skipReleaseNotes') === 'true'; } @memoize get skipWelcome(): boolean { return this.payload?.get('skipWelcome') === 'true'; } @memoize get disableWorkspaceTrust(): boolean { return !this.options.enableWorkspaceTrust; } @memoize get lastActiveProfile(): string | undefined { return this.payload?.get('lastActiveProfile'); } editSessionId: string | undefined = this.options.editSessionId; private payload: Map<string, string> | undefined; constructor( private readonly workspaceId: string, private readonly logsHome: URI, readonly options: IWorkbenchConstructionOptions, private readonly productService: IProductService ) { if (options.workspaceProvider && Array.isArray(options.workspaceProvider.payload)) { try { this.payload = new Map(options.workspaceProvider.payload); } catch (error) { onUnexpectedError(error); // possible invalid payload for map } } } private resolveExtensionHostDebugEnvironment(): IExtensionHostDebugEnvironment { const extensionHostDebugEnvironment: IExtensionHostDebugEnvironment = { params: { port: null, break: false }, debugRenderer: false, isExtensionDevelopment: false, extensionDevelopmentLocationURI: undefined, extensionDevelopmentKind: undefined }; // Fill in selected extra environmental properties if (this.payload) { for (const [key, value] of this.payload) { switch (key) { case 'extensionDevelopmentPath': if (!extensionHostDebugEnvironment.extensionDevelopmentLocationURI) { extensionHostDebugEnvironment.extensionDevelopmentLocationURI = []; } extensionHostDebugEnvironment.extensionDevelopmentLocationURI.push(URI.parse(value)); extensionHostDebugEnvironment.isExtensionDevelopment = true; break; case 'extensionDevelopmentKind': extensionHostDebugEnvironment.extensionDevelopmentKind = [<ExtensionKind>value]; break; case 'extensionTestsPath': extensionHostDebugEnvironment.extensionTestsLocationURI = URI.parse(value); break; case 'debugRenderer': extensionHostDebugEnvironment.debugRenderer = value === 'true'; break; case 'debugId': extensionHostDebugEnvironment.params.debugId = value; break; case 'inspect-brk-extensions': extensionHostDebugEnvironment.params.port = parseInt(value); extensionHostDebugEnvironment.params.break = true; break; case 'inspect-extensions': extensionHostDebugEnvironment.params.port = parseInt(value); break; case 'enableProposedApi': extensionHostDebugEnvironment.extensionEnabledProposedApi = []; break; } } } const developmentOptions = this.options.developmentOptions; if (developmentOptions && !extensionHostDebugEnvironment.isExtensionDevelopment) { if (developmentOptions.extensions?.length) { extensionHostDebugEnvironment.extensionDevelopmentLocationURI = developmentOptions.extensions.map(e => URI.revive(e)); extensionHostDebugEnvironment.isExtensionDevelopment = true; } if (developmentOptions.extensionTestsPath) { extensionHostDebugEnvironment.extensionTestsLocationURI = URI.revive(developmentOptions.extensionTestsPath); } } return extensionHostDebugEnvironment; } @memoize get filesToOpenOrCreate(): IPath<ITextEditorOptions>[] | undefined { if (this.payload) { const fileToOpen = this.payload.get('openFile'); if (fileToOpen) { const fileUri = URI.parse(fileToOpen); // Support: --goto parameter to open on line/col if (this.payload.has('gotoLineMode')) { const pathColumnAware = parseLineAndColumnAware(fileUri.path); return [{ fileUri: fileUri.with({ path: pathColumnAware.path }), options: { selection: !isUndefined(pathColumnAware.line) ? { startLineNumber: pathColumnAware.line, startColumn: pathColumnAware.column || 1 } : undefined } }]; } return [{ fileUri }]; } } return undefined; } @memoize get filesToDiff(): IPath[] | undefined { if (this.payload) { const fileToDiffPrimary = this.payload.get('diffFilePrimary'); const fileToDiffSecondary = this.payload.get('diffFileSecondary'); if (fileToDiffPrimary && fileToDiffSecondary) { return [ { fileUri: URI.parse(fileToDiffSecondary) }, { fileUri: URI.parse(fileToDiffPrimary) } ]; } } return undefined; } @memoize get filesToMerge(): IPath[] | undefined { if (this.payload) { const fileToMerge1 = this.payload.get('mergeFile1'); const fileToMerge2 = this.payload.get('mergeFile2'); const fileToMergeBase = this.payload.get('mergeFileBase'); const fileToMergeResult = this.payload.get('mergeFileResult'); if (fileToMerge1 && fileToMerge2 && fileToMergeBase && fileToMergeResult) { return [ { fileUri: URI.parse(fileToMerge1) }, { fileUri: URI.parse(fileToMerge2) }, { fileUri: URI.parse(fileToMergeBase) }, { fileUri: URI.parse(fileToMergeResult) } ]; } } return undefined; } } interface IExtensionHostDebugEnvironment { params: IExtensionHostDebugParams; debugRenderer: boolean; isExtensionDevelopment: boolean; extensionDevelopmentLocationURI?: URI[]; extensionDevelopmentKind?: ExtensionKind[]; extensionTestsLocationURI?: URI; extensionEnabledProposedApi?: string[]; }
src/vs/workbench/services/environment/browser/environmentService.ts
1
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.9618982672691345, 0.029941298067569733, 0.00016325704928021878, 0.0001847961830208078, 0.1497098207473755 ]
{ "id": 2, "code_window": [ "\tget extHostLogsPath(): URI { return joinPath(this.windowLogsPath, 'exthost'); }\n", "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\t@memoize\n", "\tget webviewExternalEndpoint(): string { return `${Schemas.vscodeWebview}://{{uuid}}`; }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/electron-sandbox/environmentService.ts", "type": "replace", "edit_start_line_idx": 98 }
#!/usr/bin/env bash if [[ "$OSTYPE" == "darwin"* ]]; then realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"; } ROOT=$(dirname $(dirname $(realpath "$0"))) else ROOT=$(dirname $(dirname $(readlink -f $0))) fi function code() { cd $ROOT if [[ "$OSTYPE" == "darwin"* ]]; then NAME=`node -p "require('./product.json').nameLong"` CODE="./.build/electron/$NAME.app/Contents/MacOS/Electron" else NAME=`node -p "require('./product.json').applicationName"` CODE=".build/electron/$NAME" fi # Get electron, compile, built-in extensions if [[ -z "${VSCODE_SKIP_PRELAUNCH}" ]]; then node build/lib/preLaunch.js fi # Manage built-in extensions if [[ "$1" == "--builtin" ]]; then exec "$CODE" build/builtin return fi ELECTRON_RUN_AS_NODE=1 \ NODE_ENV=development \ VSCODE_DEV=1 \ ELECTRON_ENABLE_LOGGING=1 \ ELECTRON_ENABLE_STACK_DUMPING=1 \ "$CODE" --inspect=5874 "$ROOT/out/cli.js" --ms-enable-electron-run-as-node . "$@" } code "$@"
scripts/code-cli.sh
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.00017576469690538943, 0.00017210262012667954, 0.00016550357395317405, 0.00017245854542125016, 0.0000035445380035525886 ]
{ "id": 2, "code_window": [ "\tget extHostLogsPath(): URI { return joinPath(this.windowLogsPath, 'exthost'); }\n", "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\t@memoize\n", "\tget webviewExternalEndpoint(): string { return `${Schemas.vscodeWebview}://{{uuid}}`; }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/electron-sandbox/environmentService.ts", "type": "replace", "edit_start_line_idx": 98 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/cpp/yarn.lock
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.00017141881107818335, 0.00017141881107818335, 0.00017141881107818335, 0.00017141881107818335, 0 ]
{ "id": 2, "code_window": [ "\tget extHostLogsPath(): URI { return joinPath(this.windowLogsPath, 'exthost'); }\n", "\n", "\t@memoize\n", "\tget extHostTelemetryLogFile(): URI {\n", "\t\treturn joinPath(this.extHostLogsPath, 'telemetry.log');\n", "\t}\n", "\n", "\t@memoize\n", "\tget webviewExternalEndpoint(): string { return `${Schemas.vscodeWebview}://{{uuid}}`; }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn joinPath(this.extHostLogsPath, 'extensionTelemetry.log');\n" ], "file_path": "src/vs/workbench/services/environment/electron-sandbox/environmentService.ts", "type": "replace", "edit_start_line_idx": 98 }
{ "ban-eval-calls": [ "vs/workbench/api/worker/extHostExtensionService.ts", "vs/base/worker/workerMain" ], "ban-function-calls": [ "vs/workbench/api/worker/extHostExtensionService.ts", "vs/base/worker/workerMain", "vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "vs/workbench/services/keybinding/test/node/keyboardMapperTestUtils.ts" ], "ban-trustedtypes-createpolicy": [ "vs/base/browser/dom.ts", "vs/base/browser/markdownRenderer.ts", "vs/base/browser/defaultWorkerFactory.ts", "vs/base/worker/workerMain.ts", "vs/editor/contrib/markdownRenderer/browser/markdownRenderer.ts", "vs/editor/contrib/stickyScroll/browser/stickyScrollWidget.ts", "vs/editor/browser/view/domLineBreaksComputer.ts", "vs/editor/browser/view/viewLayer.ts", "vs/editor/browser/widget/diffEditorWidget.ts", "vs/editor/contrib/inlineCompletions/browser/ghostTextWidget.ts", "vs/editor/browser/widget/diffReview.ts", "vs/editor/standalone/browser/colorizer.ts", "vs/workbench/api/worker/extHostExtensionService.ts", "vs/workbench/contrib/notebook/browser/view/cellParts/cellDragRenderer.ts", "vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "vs/workbench/services/extensions/browser/webWorkerExtensionHost.ts" ], "ban-worker-calls": [ "vs/base/browser/defaultWorkerFactory.ts", "vs/workbench/services/extensions/browser/webWorkerExtensionHost.ts", "vs/platform/sharedProcess/electron-browser/sharedProcessWorkerService.ts" ], "ban-domparser-parsefromstring": [ "vs/base/browser/markdownRenderer.ts", "vs/base/test/browser/markdownRenderer.test.ts" ] }
src/tsec.exemptions.json
0
https://github.com/microsoft/vscode/commit/f6a08e816d98ff72df37a1af4165742366fe2235
[ 0.00017203875177074224, 0.00016905996017158031, 0.0001663268485572189, 0.00016893711290322244, 0.000002519492682040436 ]
{ "id": 0, "code_window": [ "\n", "check_bazel_version(\"0.9.0\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "RULES_TYPESCRIPT_VERSION = \"0.10.1\"\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 18 }
workspace(name = "angular") # Using a pre-release snapshot to pick up a commit that makes all nodejs_binary # programs produce source-mapped stack traces. RULES_NODEJS_VERSION = "926349cea4cd360afcd5647ccdd09d2d2fb471aa" http_archive( name = "build_bazel_rules_nodejs", url = "https://github.com/bazelbuild/rules_nodejs/archive/%s.zip" % RULES_NODEJS_VERSION, strip_prefix = "rules_nodejs-%s" % RULES_NODEJS_VERSION, sha256 = "5ba3c8c209078c2e3f0c6aa4abd01a1a561f92a5bfda04e25604af5f4734d69d", ) load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories") check_bazel_version("0.9.0") node_repositories(package_json = ["//:package.json"]) RULES_TYPESCRIPT_VERSION = "0.10.1" http_archive( name = "build_bazel_rules_typescript", url = "https://github.com/bazelbuild/rules_typescript/archive/%s.zip" % RULES_TYPESCRIPT_VERSION, strip_prefix = "rules_typescript-%s" % RULES_TYPESCRIPT_VERSION, sha256 = "a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485", ) load("@build_bazel_rules_typescript//:defs.bzl", "ts_setup_workspace") ts_setup_workspace() local_repository( name = "rxjs", path = "node_modules/rxjs/src", ) git_repository( name = "com_github_bazelbuild_buildtools", remote = "https://github.com/bazelbuild/buildtools.git", # Note, this commit matches the version of buildifier in angular/ngcontainer # If you change this, also check if it matches the version in the angular/ngcontainer # version in /.circleci/config.yml commit = "b3b620e8bcff18ed3378cd3f35ebeb7016d71f71", ) http_archive( name = "io_bazel_rules_go", url = "https://github.com/bazelbuild/rules_go/releases/download/0.7.1/rules_go-0.7.1.tar.gz", sha256 = "341d5eacef704415386974bc82a1783a8b7ffbff2ab6ba02375e1ca20d9b031c", ) load("@io_bazel_rules_go//go:def.bzl", "go_rules_dependencies", "go_register_toolchains") go_rules_dependencies() go_register_toolchains() # Fetching the Bazel source code allows us to compile the Skylark linter http_archive( name = "io_bazel", url = "https://github.com/bazelbuild/bazel/archive/9755c72b48866ed034bd28aa033e9abd27431b1e.zip", strip_prefix = "bazel-9755c72b48866ed034bd28aa033e9abd27431b1e", sha256 = "5b8443fc3481b5fcd9e7f348e1dd93c1397f78b223623c39eb56494c55f41962", ) # We have a source dependency on the Devkit repository, because it's built with # Bazel. # This allows us to edit sources and have the effect appear immediately without # re-packaging or "npm link"ing. # Even better, things like aspects will visit the entire graph including # ts_library rules in the devkit repository. http_archive( name = "angular_devkit", url = "https://github.com/angular/devkit/archive/v0.3.1.zip", strip_prefix = "devkit-0.3.1", sha256 = "31d4b597fe9336650acf13df053c1c84dcbe9c29c6a833bcac3819cd3fd8cad3", ) http_archive( name = "org_brotli", url = "https://github.com/google/brotli/archive/v1.0.2.zip", strip_prefix = "brotli-1.0.2", sha256 = "b43d5d6bc40f2fa6c785b738d86c6bbe022732fe25196ebbe43b9653a025920d", )
WORKSPACE
1
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.9994673132896423, 0.2666822075843811, 0.00016729551134631038, 0.005586758255958557, 0.40123897790908813 ]
{ "id": 0, "code_window": [ "\n", "check_bazel_version(\"0.9.0\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "RULES_TYPESCRIPT_VERSION = \"0.10.1\"\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 18 }
<!DOCTYPE html> <html lang="en"> <head> <title>Displaying Data</title> <base href="/"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <!-- #docregion body --> <body> <app-root></app-root> </body> <!-- #enddocregion body --> </html>
aio/content/examples/displaying-data/src/index.html
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001719031424727291, 0.00016941450303420424, 0.00016692584904376417, 0.00016941450303420424, 0.0000024886467144824564 ]
{ "id": 0, "code_window": [ "\n", "check_bazel_version(\"0.9.0\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "RULES_TYPESCRIPT_VERSION = \"0.10.1\"\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 18 }
{% import "api/lib/githubLinks.html" as github -%} {% import "api/lib/paramList.html" as params -%} <!DOCTYPE html> <html> <head> <title></title> <style> body { max-width: 1000px; } h2 { margin-top: 20px; margin-bottom: 0; border-bottom: solid 1px black; } h3 { margin-top: 10px; margin-bottom: 0; padding-left: 20px; } h4 { padding-left: 30px; margin: 0; } .not-documented::after { content: "(not documented)"; font-size: small; font-style: italic; color: red; } a { color: black; text-decoration: none; } </style> </head> <body> <h1>Module Overview</h1> {% for module in doc.modules %} <h2> <code>{$ module.id $}{%- if module.public %} (public){% endif %}</code> </h2> {% for export in module.exports %} <h3 {% if export.notYetDocumented %}class="not-documented"{% endif %}> <a href="{$ github.githubHref(export, versionInfo) $}"> <code>{$ export.docType $} {$ export.name $}</code> </a> </h3> {%- if export.constructorDoc %} <h4 {% if export.constructorDoc.notYetDocumented %}class="not-documented"{% endif %}> <a href="{$ github.githubHref(export.constructorDoc, versionInfo) $}"> <code>{$ export.constructorDoc.name $}{$ params.paramList(export.constructorDoc.params) $}</code> </a> </h4> {% endif -%} {%- for member in export.members %} <h4 {% if member.notYetDocumented %}class="not-documented"{% endif %}> <a href="{$ github.githubHref(member, versionInfo) $}"> <code>{$ member.name $}{$ params.paramList(member.params) $}</code> </a> </h4> {% endfor %} {% endfor %} {% endfor %} </body> </html>
aio/tools/transforms/templates/overview-dump.template.html
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017935805954039097, 0.00017495737120043486, 0.00017032166942954063, 0.0001753095129970461, 0.000002577376790213748 ]
{ "id": 0, "code_window": [ "\n", "check_bazel_version(\"0.9.0\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "RULES_TYPESCRIPT_VERSION = \"0.10.1\"\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 18 }
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Hero } from '../model/hero'; import { HeroService } from '../model/hero.service'; @Component({ selector: 'app-heroes', templateUrl: './hero-list.component.html', styleUrls: [ './hero-list.component.css' ] }) export class HeroListComponent implements OnInit { heroes: Promise<Hero[]>; selectedHero: Hero; constructor( private router: Router, private heroService: HeroService) { } ngOnInit() { this.heroes = this.heroService.getHeroes(); } onSelect(hero: Hero) { this.selectedHero = hero; this.router.navigate(['../heroes', this.selectedHero.id ]); } }
aio/content/examples/testing/src/app/hero/hero-list.component.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001743410830385983, 0.0001731085794745013, 0.0001715154357952997, 0.00017346919048577547, 0.0000011814133813459193 ]
{ "id": 1, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/%s.zip\" % RULES_TYPESCRIPT_VERSION,\n", " strip_prefix = \"rules_typescript-%s\" % RULES_TYPESCRIPT_VERSION,\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n", "\n", "ts_setup_workspace()\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 22 }
# 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.004950249567627907, 0.00034766868338920176, 0.00016367276839446276, 0.0001694968668743968, 0.0008069314644671977 ]
{ "id": 1, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/%s.zip\" % RULES_TYPESCRIPT_VERSION,\n", " strip_prefix = \"rules_typescript-%s\" % RULES_TYPESCRIPT_VERSION,\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n", "\n", "ts_setup_workspace()\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 22 }
import { FirebaseRedirector } from './FirebaseRedirector'; describe('FirebaseRedirector', () => { it('should replace with the first matching redirect', () => { const redirector = new FirebaseRedirector([ { source: '/a/b/c', destination: '/X/Y/Z' }, { source: '/a/:foo/c', destination: '/X/:foo/Z' }, { source: '/**/:foo/c', destination: '/A/:foo/zzz' }, ]); expect(redirector.redirect('/a/b/c')).toEqual('/X/Y/Z'); expect(redirector.redirect('/a/moo/c')).toEqual('/X/moo/Z'); expect(redirector.redirect('/x/y/a/b/c')).toEqual('/A/b/zzz'); expect(redirector.redirect('/x/y/c')).toEqual('/A/y/zzz'); }); it('should return the original url if no redirect matches', () => { const redirector = new FirebaseRedirector([ { source: 'x', destination: 'X' }, { source: 'y', destination: 'Y' }, { source: 'z', destination: 'Z' }, ]); expect(redirector.redirect('a')).toEqual('a'); }); it('should recursively redirect', () => { const redirector = new FirebaseRedirector([ { source: 'a', destination: 'b' }, { source: 'b', destination: 'c' }, { source: 'c', destination: 'd' }, ]); expect(redirector.redirect('a')).toEqual('d'); }); it('should throw if stuck in an infinite loop', () => { const redirector = new FirebaseRedirector([ { source: 'a', destination: 'b' }, { source: 'b', destination: 'c' }, { source: 'c', destination: 'a' }, ]); expect(() => redirector.redirect('a')).toThrowError('infinite redirect loop'); }); });
aio/tools/firebase-test-utils/FirebaseRedirector.spec.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001737970014801249, 0.00017057839431799948, 0.0001676439424045384, 0.00016931077698245645, 0.000002652013790793717 ]
{ "id": 1, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/%s.zip\" % RULES_TYPESCRIPT_VERSION,\n", " strip_prefix = \"rules_typescript-%s\" % RULES_TYPESCRIPT_VERSION,\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n", "\n", "ts_setup_workspace()\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 22 }
// #docregion import { Component, EventEmitter, Input, Output } from '@angular/core'; // #docregion example @Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { // No aliases @Output() change = new EventEmitter<any>(); @Input() label: string; } // #enddocregion example
aio/content/examples/styleguide/src/05-13/app/heroes/shared/hero-button/hero-button.component.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017188511264976114, 0.00016941988724283874, 0.0001669546472840011, 0.00016941988724283874, 0.000002465232682880014 ]
{ "id": 1, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/%s.zip\" % RULES_TYPESCRIPT_VERSION,\n", " strip_prefix = \"rules_typescript-%s\" % RULES_TYPESCRIPT_VERSION,\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n", "\n", "ts_setup_workspace()\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "WORKSPACE", "type": "replace", "edit_start_line_idx": 22 }
// #docplaster // #docregion import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AdminComponent } from './admin.component'; import { AdminDashboardComponent } from './admin-dashboard.component'; import { ManageCrisesComponent } from './manage-crises.component'; import { ManageHeroesComponent } from './manage-heroes.component'; // #docregion admin-route import { AuthGuard } from '../auth-guard.service'; const adminRoutes: Routes = [ { path: 'admin', component: AdminComponent, canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, { path: 'heroes', component: ManageHeroesComponent }, { path: '', component: AdminDashboardComponent } ], // #enddocregion admin-route canActivateChild: [AuthGuard] // #docregion admin-route } ] } ]; @NgModule({ imports: [ RouterModule.forChild(adminRoutes) ], exports: [ RouterModule ] }) export class AdminRoutingModule {} // #enddocregion
aio/content/examples/router/src/app/admin/admin-routing.module.2.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.000211574268178083, 0.00017790019046515226, 0.00016529319691471756, 0.00017014521290548146, 0.00001699618951533921 ]
{ "id": 2, "code_window": [ "load(\"@build_bazel_rules_nodejs//:defs.bzl\", \"node_repositories\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 12 }
# 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.0009738392545841634, 0.00025100697530433536, 0.0001655521773500368, 0.0001709102507447824, 0.00017925110296346247 ]
{ "id": 2, "code_window": [ "load(\"@build_bazel_rules_nodejs//:defs.bzl\", \"node_repositories\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 12 }
/** * @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 export default [];
packages/common/locales/extra/tk.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017428754654247314, 0.00017206117627210915, 0.0001698348205536604, 0.00017206117627210915, 0.0000022263629944063723 ]
{ "id": 2, "code_window": [ "load(\"@build_bazel_rules_nodejs//:defs.bzl\", \"node_repositories\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 12 }
/** * @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 {NgLocalization} from '@angular/common'; import {ResourceLoader} from '@angular/compiler'; import {MessageBundle} from '@angular/compiler/src/i18n/message_bundle'; import {Xliff} from '@angular/compiler/src/i18n/serializers/xliff'; import {HtmlParser} from '@angular/compiler/src/ml_parser/html_parser'; import {DEFAULT_INTERPOLATION_CONFIG} from '@angular/compiler/src/ml_parser/interpolation_config'; import {DebugElement, TRANSLATIONS, TRANSLATIONS_FORMAT} from '@angular/core'; import {ComponentFixture, TestBed, async} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {SpyResourceLoader} from '../spies'; import {FrLocalization, HTML, I18nComponent, validateHtml} from './integration_common'; { describe('i18n XLIFF integration spec', () => { beforeEach(async(() => { TestBed.configureCompiler({ providers: [ SpyResourceLoader.PROVIDE, FrLocalization.PROVIDE, {provide: TRANSLATIONS, useValue: XLIFF_TOMERGE}, {provide: TRANSLATIONS_FORMAT, useValue: 'xliff'}, ] }); TestBed.configureTestingModule({declarations: [I18nComponent]}); })); it('should extract from templates', () => { const catalog = new MessageBundle(new HtmlParser, [], {}); const serializer = new Xliff(); catalog.updateFromTemplate(HTML, 'file.ts', DEFAULT_INTERPOLATION_CONFIG); expect(catalog.write(serializer)).toContain(XLIFF_EXTRACTED); }); it('should translate templates', () => { const tb: ComponentFixture<I18nComponent> = TestBed.overrideTemplate(I18nComponent, HTML).createComponent(I18nComponent); const cmp: I18nComponent = tb.componentInstance; const el: DebugElement = tb.debugElement; validateHtml(tb, cmp, el); }); }); } const XLIFF_TOMERGE = ` <trans-unit id="3cb04208df1c2f62553ed48e75939cf7107f9dad" datatype="html"> <source>i18n attribute on tags</source> <target>attributs i18n sur les balises</target> </trans-unit> <trans-unit id="52895b1221effb3f3585b689f049d2784d714952" datatype="html"> <source>nested</source> <target>imbriqué</target> </trans-unit> <trans-unit id="88d5f22050a9df477ee5646153558b3a4862d47e" datatype="html"> <source>nested</source> <target>imbriqué</target> <note priority="1" from="meaning">different meaning</note> </trans-unit> <trans-unit id="34fec9cc62e28e8aa6ffb306fa8569ef0a8087fe" datatype="html"> <source><x id="START_ITALIC_TEXT" ctype="x-i" equiv-text="&lt;i&gt;"/>with placeholders<x id="CLOSE_ITALIC_TEXT" ctype="x-i" equiv-text="&lt;/i&gt;"/></source> <target><x id="START_ITALIC_TEXT" ctype="x-i"/>avec des espaces réservés<x id="CLOSE_ITALIC_TEXT" ctype="x-i"/></target> </trans-unit> <trans-unit id="651d7249d3a225037eb66f3433d98ad4a86f0a22" datatype="html"> <source><x id="START_TAG_DIV" ctype="x-div"/>with <x id="START_TAG_DIV" ctype="x-div"/>nested<x id="CLOSE_TAG_DIV" ctype="x-div"/> placeholders<x id="CLOSE_TAG_DIV" ctype="x-div"/></source> <target><x id="START_TAG_DIV" ctype="x-div"/>with <x id="START_TAG_DIV" ctype="x-div"/>nested<x id="CLOSE_TAG_DIV" ctype="x-div"/> placeholders<x id="CLOSE_TAG_DIV" ctype="x-div"/></target> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">11</context> </context-group> </trans-unit> <trans-unit id="1fe4616cce80a57c7707bac1c97054aa8e244a67" datatype="html"> <source>on not translatable node</source> <target>sur des balises non traductibles</target> </trans-unit> <trans-unit id="67162b5af5f15fd0eb6480c88688dafdf952b93a" datatype="html"> <source>on translatable node</source> <target>sur des balises traductibles</target> </trans-unit> <trans-unit id="dc5536bb9e0e07291c185a0d306601a2ecd4813f" datatype="html"> <source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/>} }</source> <target>{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<x id="START_BOLD_TEXT" ctype="x-b"/>beaucoup<x id="CLOSE_BOLD_TEXT" ctype="x-b"/>} }</target> </trans-unit> <trans-unit id="49feb201083cbd2c8bfc48a4ae11f105fb984876" datatype="html"> <source> <x id="ICU" equiv-text="{sex, select, male {...} female {...}}"/> </source> <target><x id="ICU"/></target> </trans-unit> <trans-unit id="f3be30eb9a18f6e336cc3ca4dd66bbc3a35c5f97" datatype="html"> <source>{VAR_SELECT, select, other {other} male {m} female {f} }</source> <target>{VAR_SELECT, select, other {autre} male {homme} female {femme}}</target> </trans-unit> <trans-unit id="cc16e9745fa0b95b2ebc2f18b47ed8e64fe5f0f9" datatype="html"> <source> <x id="ICU" equiv-text="{sexB, select, m {...} f {...}}"/> </source> <target><x id="ICU"/></target> </trans-unit> <trans-unit id="4573f2edb0329d69afc2ab8c73c71e2f8b08f807" datatype="html"> <source>{VAR_SELECT, select, male {m} female {f} }</source> <target>{VAR_SELECT, select, male {homme} female {femme} }</target> </trans-unit> <trans-unit id="d9879678f727b244bc7c7e20f22b63d98cb14890" datatype="html"> <source><x id="INTERPOLATION" equiv-text="{{ &quot;count = &quot; + count }}"/></source> <target><x id="INTERPOLATION"/></target> </trans-unit> <trans-unit id="50dac33dc6fc0578884baac79d875785ed77c928" datatype="html"> <source>sex = <x id="INTERPOLATION" equiv-text="{{ sex }}"/></source> <target>sexe = <x id="INTERPOLATION"/></target> </trans-unit> <trans-unit id="a46f833b1fe6ca49e8b97c18f4b7ea0b930c9383" datatype="html"> <source><x id="CUSTOM_NAME" equiv-text="{{ &quot;custom name&quot; //i18n(ph=&quot;CUSTOM_NAME&quot;) }}"/></source> <target><x id="CUSTOM_NAME"/></target> </trans-unit> <trans-unit id="2ec983b4893bcd5b24af33bebe3ecba63868453c" datatype="html"> <source>in a translatable section</source> <target>dans une section traductible</target> </trans-unit> <trans-unit id="7f6272480ea8e7ffab548da885ab8105ee2caa93" datatype="html"> <source> <x id="START_HEADING_LEVEL1" ctype="x-h1" equiv-text="&lt;h1&gt;"/>Markers in html comments<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1" equiv-text="&lt;/h1&gt;"/> <x id="START_TAG_DIV" ctype="x-div" equiv-text="&lt;div&gt;"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="&lt;/div&gt;"/> <x id="START_TAG_DIV_1" ctype="x-div" equiv-text="&lt;div&gt;"/><x id="ICU" equiv-text="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="&lt;/div&gt;"/> </source> <target> <x id="START_HEADING_LEVEL1" ctype="x-h1"/>Balises dans les commentaires html<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1"/> <x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/> <x id="START_TAG_DIV_1" ctype="x-div"/><x id="ICU"/><x id="CLOSE_TAG_DIV" ctype="x-div"/> </target> </trans-unit> <trans-unit id="93a30c67d4e6c9b37aecfe2ac0f2b5d366d7b520" datatype="html"> <source>it <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/>should<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/> work</source> <target>ca <x id="START_BOLD_TEXT" ctype="x-b"/>devrait<x id="CLOSE_BOLD_TEXT" ctype="x-b"/> marcher</target> </trans-unit> <trans-unit id="i18n16" datatype="html"> <source>with an explicit ID</source> <target>avec un ID explicite</target> </trans-unit> <trans-unit id="i18n17" datatype="html"> <source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/>} }</source> <target>{VAR_PLURAL, plural, =0 {zero} =1 {un} =2 {deux} other {<x id="START_BOLD_TEXT" ctype="x-b"/>beaucoup<x id="CLOSE_BOLD_TEXT" ctype="x-b"/>} }</target> </trans-unit> <trans-unit id="2370d995bdcc1e7496baa32df20654aff65c2d10" datatype="html"> <source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <x id="INTERPOLATION" equiv-text="{{response.getItemsList().length}}"/> results} }</source> <target>{VAR_PLURAL, plural, =0 {Pas de réponse} =1 {une réponse} other {Found <x id="INTERPOLATION"/> réponse} }</target> <note priority="1" from="description">desc</note> </trans-unit> <trans-unit id="296ab5eab8d370822488c152586db3a5875ee1a2" datatype="html"> <source>foo<x id="START_LINK" ctype="x-a" equiv-text="&lt;a&gt;"/>bar<x id="CLOSE_LINK" ctype="x-a" equiv-text="&lt;/a&gt;"/></source> <target>FOO<x id="START_LINK" ctype="x-a"/>BAR<x id="CLOSE_LINK" ctype="x-a"/></target> </trans-unit> <trans-unit id="2e013b311caa0916478941a985887e091d8288b6" datatype="html"> <source><x id="MAP NAME" equiv-text="{{ &apos;test&apos; //i18n(ph=&quot;map name&quot;) }}"/></source> <target><x id="MAP NAME"/></target> </trans-unit>`; const XLIFF_EXTRACTED = ` <trans-unit id="3cb04208df1c2f62553ed48e75939cf7107f9dad" datatype="html"> <source>i18n attribute on tags</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">3</context> </context-group> </trans-unit> <trans-unit id="52895b1221effb3f3585b689f049d2784d714952" datatype="html"> <source>nested</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">5</context> </context-group> </trans-unit> <trans-unit id="88d5f22050a9df477ee5646153558b3a4862d47e" datatype="html"> <source>nested</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">7</context> </context-group> <note priority="1" from="meaning">different meaning</note> </trans-unit> <trans-unit id="34fec9cc62e28e8aa6ffb306fa8569ef0a8087fe" datatype="html"> <source><x id="START_ITALIC_TEXT" ctype="x-i" equiv-text="&lt;i&gt;"/>with placeholders<x id="CLOSE_ITALIC_TEXT" ctype="x-i" equiv-text="&lt;/i&gt;"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">9</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">10</context> </context-group> </trans-unit> <trans-unit id="651d7249d3a225037eb66f3433d98ad4a86f0a22" datatype="html"> <source><x id="START_TAG_DIV" ctype="x-div" equiv-text="&lt;div&gt;"/>with <x id="START_TAG_DIV" ctype="x-div" equiv-text="&lt;div&gt;"/>nested<x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="&lt;/div&gt;"/> placeholders<x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="&lt;/div&gt;"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">11</context> </context-group> </trans-unit> <trans-unit id="1fe4616cce80a57c7707bac1c97054aa8e244a67" datatype="html"> <source>on not translatable node</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">14</context> </context-group> </trans-unit> <trans-unit id="67162b5af5f15fd0eb6480c88688dafdf952b93a" datatype="html"> <source>on translatable node</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">15</context> </context-group> </trans-unit> <trans-unit id="dc5536bb9e0e07291c185a0d306601a2ecd4813f" datatype="html"> <source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/>} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">20</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">37</context> </context-group> </trans-unit> <trans-unit id="49feb201083cbd2c8bfc48a4ae11f105fb984876" datatype="html"> <source> <x id="ICU" equiv-text="{sex, select, male {...} female {...} other {...}}"/> </source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">22</context> </context-group> </trans-unit> <trans-unit id="f3be30eb9a18f6e336cc3ca4dd66bbc3a35c5f97" datatype="html"> <source>{VAR_SELECT, select, male {m} female {f} other {other} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">23</context> </context-group> </trans-unit> <trans-unit id="cc16e9745fa0b95b2ebc2f18b47ed8e64fe5f0f9" datatype="html"> <source> <x id="ICU" equiv-text="{sexB, select, male {...} female {...}}"/> </source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">25</context> </context-group> </trans-unit> <trans-unit id="4573f2edb0329d69afc2ab8c73c71e2f8b08f807" datatype="html"> <source>{VAR_SELECT, select, male {m} female {f} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">26</context> </context-group> </trans-unit> <trans-unit id="d9879678f727b244bc7c7e20f22b63d98cb14890" datatype="html"> <source><x id="INTERPOLATION" equiv-text="{{ &quot;count = &quot; + count }}"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">29</context> </context-group> </trans-unit> <trans-unit id="50dac33dc6fc0578884baac79d875785ed77c928" datatype="html"> <source>sex = <x id="INTERPOLATION" equiv-text="{{ sex }}"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">30</context> </context-group> </trans-unit> <trans-unit id="a46f833b1fe6ca49e8b97c18f4b7ea0b930c9383" datatype="html"> <source><x id="CUSTOM_NAME" equiv-text="{{ &quot;custom name&quot; //i18n(ph=&quot;CUSTOM_NAME&quot;) }}"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">31</context> </context-group> </trans-unit> <trans-unit id="2ec983b4893bcd5b24af33bebe3ecba63868453c" datatype="html"> <source>in a translatable section</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">36</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">54</context> </context-group> </trans-unit> <trans-unit id="7f6272480ea8e7ffab548da885ab8105ee2caa93" datatype="html"> <source> <x id="START_HEADING_LEVEL1" ctype="x-h1" equiv-text="&lt;h1&gt;"/>Markers in html comments<x id="CLOSE_HEADING_LEVEL1" ctype="x-h1" equiv-text="&lt;/h1&gt;"/> <x id="START_TAG_DIV" ctype="x-div" equiv-text="&lt;div&gt;"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="&lt;/div&gt;"/> <x id="START_TAG_DIV_1" ctype="x-div" equiv-text="&lt;div&gt;"/><x id="ICU" equiv-text="{count, plural, =0 {...} =1 {...} =2 {...} other {...}}"/><x id="CLOSE_TAG_DIV" ctype="x-div" equiv-text="&lt;/div&gt;"/> </source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">34</context> </context-group> </trans-unit> <trans-unit id="93a30c67d4e6c9b37aecfe2ac0f2b5d366d7b520" datatype="html"> <source>it <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/>should<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/> work</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">40</context> </context-group> </trans-unit> <trans-unit id="i18n16" datatype="html"> <source>with an explicit ID</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">42</context> </context-group> </trans-unit> <trans-unit id="i18n17" datatype="html"> <source>{VAR_PLURAL, plural, =0 {zero} =1 {one} =2 {two} other {<x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/>many<x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/>} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">43</context> </context-group> </trans-unit> <trans-unit id="2370d995bdcc1e7496baa32df20654aff65c2d10" datatype="html"> <source>{VAR_PLURAL, plural, =0 {Found no results} =1 {Found one result} other {Found <x id="INTERPOLATION" equiv-text="{{response.getItemsList().length}}"/> results} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">46</context> </context-group> <note priority="1" from="description">desc</note> </trans-unit> <trans-unit id="296ab5eab8d370822488c152586db3a5875ee1a2" datatype="html"> <source>foo<x id="START_LINK" ctype="x-a" equiv-text="&lt;a&gt;"/>bar<x id="CLOSE_LINK" ctype="x-a" equiv-text="&lt;/a&gt;"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">54</context> </context-group> </trans-unit> <trans-unit id="2e013b311caa0916478941a985887e091d8288b6" datatype="html"> <source><x id="MAP NAME" equiv-text="{{ &apos;test&apos; //i18n(ph=&quot;map name&quot;) }}"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">56</context> </context-group> </trans-unit>`;
packages/compiler/test/i18n/integration_xliff_spec.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0003045932680834085, 0.0001744245528243482, 0.00016635190695524216, 0.00017025446868501604, 0.000022603759134653956 ]
{ "id": 2, "code_window": [ "load(\"@build_bazel_rules_nodejs//:defs.bzl\", \"node_repositories\")\n", "node_repositories(package_json = [\"//:package.json\"])\n", "\n", "http_archive(\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "git_repository(\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 12 }
/* AppComponent's private CSS styles */ h1 { font-size: 1.2em; color: #999; margin-bottom: 0; } h2 { font-size: 2em; margin-top: 0; padding-top: 0; } nav a { padding: 5px 10px; text-decoration: none; margin-top: 10px; display: inline-block; background-color: #eee; border-radius: 4px; } nav a:visited, a:link { color: #607D8B; } nav a:hover { color: #039be5; background-color: #CFD8DC; } nav a.active { color: #039be5; }
aio/content/examples/toh-pt6/src/app/app.component.css
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017426379781682044, 0.00017376989126205444, 0.00017350127745885402, 0.00017354462761431932, 3.4968596196449653e-7 ]
{ "id": 3, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.10.1.zip\",\n", " strip_prefix = \"rules_typescript-0.10.1\",\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 14 }
# 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.005221675615757704, 0.00031681606196798384, 0.00016233856149483472, 0.00016769958892837167, 0.0008180681616067886 ]
{ "id": 3, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.10.1.zip\",\n", " strip_prefix = \"rules_typescript-0.10.1\",\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 14 }
aio/content/examples/toh-pt3/src/app/hero-detail/hero-detail.component.css
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0005379291833378375, 0.0005379291833378375, 0.0005379291833378375, 0.0005379291833378375, 0 ]
{ "id": 3, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.10.1.zip\",\n", " strip_prefix = \"rules_typescript-0.10.1\",\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 14 }
<!-- #docregion --> <h3>Binding innerHTML</h3> <p>Bound value:</p> <p class="e2e-inner-html-interpolated">{{htmlSnippet}}</p> <p>Result of binding to innerHTML:</p> <p class="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p>
aio/content/examples/security/src/app/inner-html-binding.component.html
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00016572291497141123, 0.00016572291497141123, 0.00016572291497141123, 0.00016572291497141123, 0 ]
{ "id": 3, "code_window": [ " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.10.1.zip\",\n", " strip_prefix = \"rules_typescript-0.10.1\",\n", " sha256 = \"a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485\",\n", ")\n", "\n", "load(\"@build_bazel_rules_typescript//:defs.bzl\", \"ts_setup_workspace\")\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " commit = \"d3cc5cd72d89aee0e4c2553ae1b99c707ecbef4e\",\n", " remote = \"https://github.com/bazelbuild/rules_typescript\",\n" ], "file_path": "integration/bazel/WORKSPACE", "type": "replace", "edit_start_line_idx": 14 }
module.exports = function markBarredODocsAsPrivate() { return { $runAfter: ['readTypeScriptModules'], $runBefore: ['adding-extra-docs'], $process: function(docs) { docs.forEach(doc => { if (doc.name && doc.name.indexOf('ɵ') === 0) { doc.privateExport = true; } }); } }; };
aio/tools/transforms/angular-api-package/processors/markBarredODocsAsPrivate.js
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00016845330537762493, 0.00016780504665803164, 0.00016715678793843836, 0.00016780504665803164, 6.482587195932865e-7 ]
{ "id": 4, "code_window": [ " # Expose the v8 garbage collection API to JS.\n", " \"--node_options=--expose-gc\"\n", "]\n", "\n", "def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file,\n", " locale=None, i18n_args=[]):\n", " \"\"\"Helper function to create the ngc action.\n", "\n", " This is exposed for google3 to wire up i18n replay rules, and is not intended\n", " as part of the public API.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node_opts, locale=None, i18n_args=[]):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 123 }
# 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.9972571730613708, 0.3395218849182129, 0.00016695067461114377, 0.0034405456390231848, 0.43165189027786255 ]
{ "id": 4, "code_window": [ " # Expose the v8 garbage collection API to JS.\n", " \"--node_options=--expose-gc\"\n", "]\n", "\n", "def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file,\n", " locale=None, i18n_args=[]):\n", " \"\"\"Helper function to create the ngc action.\n", "\n", " This is exposed for google3 to wire up i18n replay rules, and is not intended\n", " as part of the public API.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node_opts, locale=None, i18n_args=[]):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 123 }
{ "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "lib": ["es2015", "dom"], "experimentalDecorators": true, "emitDecoratorMetadata": true, "outDir": "dist", "types": ["node"], "rootDir": "." }, "files": [ "src/app.ts", "src/main.ts" ] }
integration/injectable-def/tsconfig-app.json
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001699944114079699, 0.00016824950580485165, 0.00016650458564981818, 0.00016824950580485165, 0.000001744912879075855 ]
{ "id": 4, "code_window": [ " # Expose the v8 garbage collection API to JS.\n", " \"--node_options=--expose-gc\"\n", "]\n", "\n", "def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file,\n", " locale=None, i18n_args=[]):\n", " \"\"\"Helper function to create the ngc action.\n", "\n", " This is exposed for google3 to wire up i18n replay rules, and is not intended\n", " as part of the public API.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node_opts, locale=None, i18n_args=[]):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 123 }
/** * @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 [ 'uz-Latn', [ ['TO', 'TK'], , ], , [ ['Y', 'D', 'S', 'C', 'P', 'J', 'S'], ['Yak', 'Dush', 'Sesh', 'Chor', 'Pay', 'Jum', 'Shan'], ['yakshanba', 'dushanba', 'seshanba', 'chorshanba', 'payshanba', 'juma', 'shanba'], ['Ya', 'Du', 'Se', 'Ch', 'Pa', 'Ju', 'Sh'] ], , [ ['Y', 'F', 'M', 'A', 'M', 'I', 'I', 'A', 'S', 'O', 'N', 'D'], ['yan', 'fev', 'mar', 'apr', 'may', 'iyn', 'iyl', 'avg', 'sen', 'okt', 'noy', 'dek'], [ 'yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avgust', 'sentabr', 'oktabr', 'noyabr', 'dekabr' ] ], [ ['Y', 'F', 'M', 'A', 'M', 'I', 'I', 'A', 'S', 'O', 'N', 'D'], ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'Iyn', 'Iyl', 'Avg', 'Sen', 'Okt', 'Noy', 'Dek'], [ 'Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'Iyun', 'Iyul', 'Avgust', 'Sentabr', 'Oktabr', 'Noyabr', 'Dekabr' ] ], [['m.a.', 'milodiy'], , ['miloddan avvalgi', 'milodiy']], 1, [6, 0], ['dd/MM/yy', 'd-MMM, y', 'd-MMMM, y', 'EEEE, d-MMMM, y'], ['HH:mm', 'HH:mm:ss', 'H:mm:ss (z)', 'H:mm:ss (zzzz)'], [ '{1}, {0}', , , ], [',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'son emas', ':'], ['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'], 'soʻm', 'O‘zbekiston so‘mi', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$'], 'UZS': ['soʻm']}, plural ];
packages/common/locales/uz-Latn.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017313506396021694, 0.0001709405769361183, 0.0001688922056928277, 0.00017107849998865277, 0.0000013868703945263405 ]
{ "id": 4, "code_window": [ " # Expose the v8 garbage collection API to JS.\n", " \"--node_options=--expose-gc\"\n", "]\n", "\n", "def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file,\n", " locale=None, i18n_args=[]):\n", " \"\"\"Helper function to create the ngc action.\n", "\n", " This is exposed for google3 to wire up i18n replay rules, and is not intended\n", " as part of the public API.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node_opts, locale=None, i18n_args=[]):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 123 }
{ "extends": "../tsconfig-build.json", "compilerOptions": { "baseUrl": ".", "rootDir": ".", "paths": { "@angular/core": ["../../dist/packages/core"], "@angular/common": ["../../dist/packages/common"] }, "outDir": "../../dist/packages/service-worker" }, "files": [ "public_api.ts", "../../node_modules/zone.js/dist/zone.js.d.ts" ], "angularCompilerOptions": { "annotateForClosureCompiler": true, "strictMetadataEmit": false, "flatModuleOutFile": "service-worker.js", "flatModuleId": "@angular/service-worker", "skipTemplateCodegen": true } }
packages/service-worker/tsconfig-build.json
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017046088760253042, 0.00016924680676311255, 0.00016837764997035265, 0.00016890188271645457, 8.847595154293231e-7 ]
{ "id": 5, "code_window": [ " label: the label of the ng_module being compiled\n", " inputs: passed to the ngc action's inputs\n", " outputs: passed to the ngc action's outputs\n", " messages_out: produced xmb files\n", " tsconfig_file: tsconfig file with settings used for the compilation\n", " locale: i18n locale, or None\n", " i18n_args: additional command-line arguments to ngc\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " node_opts: list of strings, extra nodejs options.\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "add", "edit_start_line_idx": 136 }
# 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.9974192380905151, 0.13075919449329376, 0.00016391827375628054, 0.0054201059974730015, 0.3080693185329437 ]
{ "id": 5, "code_window": [ " label: the label of the ng_module being compiled\n", " inputs: passed to the ngc action's inputs\n", " outputs: passed to the ngc action's outputs\n", " messages_out: produced xmb files\n", " tsconfig_file: tsconfig file with settings used for the compilation\n", " locale: i18n locale, or None\n", " i18n_args: additional command-line arguments to ngc\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " node_opts: list of strings, extra nodejs options.\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "add", "edit_start_line_idx": 136 }
'use strict'; // necessary for es6 output in node import { browser, element, by } from 'protractor'; describe('QuickStart E2E Tests', function () { let expectedMsg = 'Hello from Angular App with Webpack'; beforeEach(function () { browser.get(''); }); it(`should display: ${expectedMsg}`, function () { expect(element(by.css('h1')).getText()).toEqual(expectedMsg); }); it('should display an image', function () { expect(element(by.css('img')).isPresent()).toBe(true); }); });
aio/content/examples/webpack/e2e-spec.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001754117402015254, 0.00017190021753776819, 0.0001693023950792849, 0.00017098654643632472, 0.000002576448878244264 ]
{ "id": 5, "code_window": [ " label: the label of the ng_module being compiled\n", " inputs: passed to the ngc action's inputs\n", " outputs: passed to the ngc action's outputs\n", " messages_out: produced xmb files\n", " tsconfig_file: tsconfig file with settings used for the compilation\n", " locale: i18n locale, or None\n", " i18n_args: additional command-line arguments to ngc\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " node_opts: list of strings, extra nodejs options.\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "add", "edit_start_line_idx": 136 }
aio/content/examples/toh-pt2/example-config.json
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017514752107672393, 0.00017514752107672393, 0.00017514752107672393, 0.00017514752107672393, 0 ]
{ "id": 5, "code_window": [ " label: the label of the ng_module being compiled\n", " inputs: passed to the ngc action's inputs\n", " outputs: passed to the ngc action's outputs\n", " messages_out: produced xmb files\n", " tsconfig_file: tsconfig file with settings used for the compilation\n", " locale: i18n locale, or None\n", " i18n_args: additional command-line arguments to ngc\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " node_opts: list of strings, extra nodejs options.\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "add", "edit_start_line_idx": 136 }
{ "name": "cli-hello-world", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod --build-optimizer", "test": "ng test --single-run", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "file:../../dist/packages-dist/animations", "@angular/common": "file:../../dist/packages-dist/common", "@angular/compiler": "file:../../dist/packages-dist/compiler", "@angular/core": "file:../../dist/packages-dist/core", "@angular/forms": "file:../../dist/packages-dist/forms", "@angular/http": "file:../../dist/packages-dist/http", "@angular/platform-browser": "file:../../dist/packages-dist/platform-browser", "@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic", "@angular/router": "file:../../dist/packages-dist/router", "core-js": "^2.4.1", "rxjs": "^5.5.6", "zone.js": "^0.8.19" }, "devDependencies": { "@angular/cli": "1.6.6", "@angular/compiler-cli": "file:../../dist/packages-dist/compiler-cli", "@angular/language-service": "file:../../dist/packages-dist/language-service", "@types/jasmine": "~2.8.3", "@types/jasminewd2": "~2.0.2", "@types/node": "~6.0.60", "codelyzer": "^4.0.1", "jasmine-core": "~2.8.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~2.0.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "^1.2.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.1.2", "ts-node": "~4.1.0", "tslint": "~5.9.1", "typescript": "2.4.2" } }
integration/cli-hello-world/package.json
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017365902021992952, 0.00017127943283412606, 0.0001700067223282531, 0.00017083824786823243, 0.0000012798949455827824 ]
{ "id": 6, "code_window": [ " (label, locale))\n", " else:\n", " supports_workers = str(int(ctx.attr._supports_workers))\n", "\n", " arguments = list(_EXTRA_NODE_OPTIONS_FLAGS)\n", " # One at-sign makes this a params-file, enabling the worker strategy.\n", " # Two at-signs escapes the argument so it's passed through to ngc\n", " # rather than the contents getting expanded.\n", " if supports_workers == \"1\":\n", " arguments += [\"@@\" + tsconfig_file.path]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " arguments = (list(_EXTRA_NODE_OPTIONS_FLAGS) +\n", " [\"--node_options=%s\" % opt for opt in node_opts])\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 154 }
# 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.9984896183013916, 0.10665684938430786, 0.00016443409549538046, 0.0003462007734924555, 0.3027351200580597 ]
{ "id": 6, "code_window": [ " (label, locale))\n", " else:\n", " supports_workers = str(int(ctx.attr._supports_workers))\n", "\n", " arguments = list(_EXTRA_NODE_OPTIONS_FLAGS)\n", " # One at-sign makes this a params-file, enabling the worker strategy.\n", " # Two at-signs escapes the argument so it's passed through to ngc\n", " # rather than the contents getting expanded.\n", " if supports_workers == \"1\":\n", " arguments += [\"@@\" + tsconfig_file.path]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " arguments = (list(_EXTRA_NODE_OPTIONS_FLAGS) +\n", " [\"--node_options=%s\" % opt for opt in node_opts])\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 154 }
/** * @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 export default [ [ ['del mediodía', 'de la madrugada', 'de la mañana', 'de la tarde', 'de la noche'], , ], [ ['mediodía', 'madrugada', 'mañana', 'tarde', 'noche'], , ], ['12:00', ['00:00', '06:00'], ['06:00', '12:00'], ['12:00', '20:00'], ['20:00', '24:00']] ];
packages/common/locales/extra/es-BZ.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001736624981276691, 0.00017231341917067766, 0.00017014943296089768, 0.00017312829731963575, 0.000001545625650578586 ]
{ "id": 6, "code_window": [ " (label, locale))\n", " else:\n", " supports_workers = str(int(ctx.attr._supports_workers))\n", "\n", " arguments = list(_EXTRA_NODE_OPTIONS_FLAGS)\n", " # One at-sign makes this a params-file, enabling the worker strategy.\n", " # Two at-signs escapes the argument so it's passed through to ngc\n", " # rather than the contents getting expanded.\n", " if supports_workers == \"1\":\n", " arguments += [\"@@\" + tsconfig_file.path]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " arguments = (list(_EXTRA_NODE_OPTIONS_FLAGS) +\n", " [\"--node_options=%s\" % opt for opt in node_opts])\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 154 }
export const runTests = (specFiles: string[], helpers?: string[]) => { // We can't use `import` here, because of the following mess: // - GitHub project `jasmine/jasmine` is `jasmine-core` on npm and its typings `@types/jasmine`. // - GitHub project `jasmine/jasmine-npm` is `jasmine` on npm and has no typings. // // Using `import...from 'jasmine'` here, would import from `@types/jasmine` (which refers to the // `jasmine-core` module and the `jasmine` module). // tslint:disable-next-line: no-var-requires variable-name const Jasmine = require('jasmine'); const config = { helpers, random: true, spec_files: specFiles, stopSpecOnExpectationFailure: true, }; process.on('unhandledRejection', (reason: any) => console.log('Unhandled rejection:', reason)); const runner = new Jasmine(); runner.loadConfig(config); runner.onComplete((passed: boolean) => process.exit(passed ? 0 : 1)); runner.execute(); };
aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/run-tests.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017515168292447925, 0.00017186587501782924, 0.00016543336096219718, 0.00017501262482255697, 0.000004548838660412002 ]
{ "id": 6, "code_window": [ " (label, locale))\n", " else:\n", " supports_workers = str(int(ctx.attr._supports_workers))\n", "\n", " arguments = list(_EXTRA_NODE_OPTIONS_FLAGS)\n", " # One at-sign makes this a params-file, enabling the worker strategy.\n", " # Two at-signs escapes the argument so it's passed through to ngc\n", " # rather than the contents getting expanded.\n", " if supports_workers == \"1\":\n", " arguments += [\"@@\" + tsconfig_file.path]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " arguments = (list(_EXTRA_NODE_OPTIONS_FLAGS) +\n", " [\"--node_options=%s\" % opt for opt in node_opts])\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 154 }
var Package = require('dgeni').Package; var jsdocPackage = require('dgeni-packages/jsdoc'); module.exports = new Package('examples', [jsdocPackage]) .factory(require('./inline-tag-defs/example')) .factory(require('./services/parseArgString')) .factory(require('./services/example-map')) .factory(require('./file-readers/example-reader')) .factory(require('./services/region-parser')) .factory(require('./services/getExampleRegion')) .processor(require('./processors/collect-examples')) .processor(require('./processors/render-examples')) .config(function(readFilesProcessor, exampleFileReader) { readFilesProcessor.fileReaders.push(exampleFileReader); }) .config(function(inlineTagProcessor, exampleInlineTagDef) { inlineTagProcessor.inlineTagDefinitions.push(exampleInlineTagDef); }) .config(function(computePathsProcessor) { computePathsProcessor.pathTemplates.push( {docTypes: ['example-region'], getPath: function() {}, getOutputPath: function() {}}); });
aio/tools/transforms/examples-package/index.js
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017649891378823668, 0.00017513711645733565, 0.00017305172514170408, 0.00017586073954589665, 0.0000014974399391576299 ]
{ "id": 7, "code_window": [ " compiler = ctx.executable.compiler,\n", " )\n", "\n", " return None\n", "\n", "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file):\n", " # Give the Angular compiler all the user-listed assets\n", " file_inputs = list(ctx.files.assets)\n", "\n", " # The compiler only needs to see TypeScript sources from the npm dependencies,\n", " # but may need to look at package.json and ngsummary.json files as well.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 201 }
# 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.9992337226867676, 0.2433604747056961, 0.00016606126155238599, 0.0030830809846520424, 0.40568676590919495 ]
{ "id": 7, "code_window": [ " compiler = ctx.executable.compiler,\n", " )\n", "\n", " return None\n", "\n", "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file):\n", " # Give the Angular compiler all the user-listed assets\n", " file_inputs = list(ctx.files.assets)\n", "\n", " # The compiler only needs to see TypeScript sources from the npm dependencies,\n", " # but may need to look at package.json and ngsummary.json files as well.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 201 }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HeroesComponent } from './heroes/heroes.component'; import { HeroDetailComponent } from './hero-detail/hero-detail.component'; import { HeroService } from './hero.service'; import { MessageService } from './message.service'; import { MessagesComponent } from './messages/messages.component'; @NgModule({ declarations: [ AppComponent, HeroesComponent, HeroDetailComponent, MessagesComponent ], imports: [ BrowserModule, FormsModule ], // #docregion providers // #docregion providers-heroservice providers: [ HeroService, // #enddocregion providers-heroservice MessageService // #docregion providers-heroservice ], // #enddocregion providers-heroservice // #enddocregion providers bootstrap: [ AppComponent ] }) export class AppModule { }
aio/content/examples/toh-pt4/src/app/app.module.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017462208052165806, 0.0001706309849396348, 0.00016657778178341687, 0.00017066203872673213, 0.0000028454169296310283 ]
{ "id": 7, "code_window": [ " compiler = ctx.executable.compiler,\n", " )\n", "\n", " return None\n", "\n", "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file):\n", " # Give the Angular compiler all the user-listed assets\n", " file_inputs = list(ctx.files.assets)\n", "\n", " # The compiler only needs to see TypeScript sources from the npm dependencies,\n", " # but may need to look at package.json and ngsummary.json files as well.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 201 }
/** * @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 export default [ [ ['usiku', 'mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni', 'usiku'], ['saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni', 'usiku'], ], [ ['saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni', 'usiku'], ['saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'alasiri', 'jioni', 'usiku'], ['saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni', 'usiku'] ], [ '00:00', '12:00', ['04:00', '07:00'], ['07:00', '12:00'], ['12:00', '16:00'], ['16:00', '19:00'], ['19:00', '04:00'] ] ];
packages/common/locales/extra/sw-UG.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017385385581292212, 0.00017221491725649685, 0.0001711100194370374, 0.00017168086196761578, 0.0000011821074394902098 ]
{ "id": 7, "code_window": [ " compiler = ctx.executable.compiler,\n", " )\n", "\n", " return None\n", "\n", "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file):\n", " # Give the Angular compiler all the user-listed assets\n", " file_inputs = list(ctx.files.assets)\n", "\n", " # The compiler only needs to see TypeScript sources from the npm dependencies,\n", " # but may need to look at package.json and ngsummary.json files as well.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 201 }
nav#main-table-of-contents { width: 200px; height: 900px; position: fixed; right: 0; top: 50px; bottom: 100px; margin-left: 32px; background-color: $blue; }
aio/src/styles/1-layouts/_table-of-contents.scss
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017241976456716657, 0.00017197593115270138, 0.00017153211229015142, 0.00017197593115270138, 4.438261385075748e-7 ]
{ "id": 8, "code_window": [ " # Collect the inputs and summary files from our deps\n", " action_inputs = depset(file_inputs,\n", " transitive = [inputs] + [dep.collect_summaries_aspect_result for dep in ctx.attr.deps\n", " if hasattr(dep, \"collect_summaries_aspect_result\")])\n", "\n", " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 220 }
workspace(name = "angular") # Using a pre-release snapshot to pick up a commit that makes all nodejs_binary # programs produce source-mapped stack traces. RULES_NODEJS_VERSION = "926349cea4cd360afcd5647ccdd09d2d2fb471aa" http_archive( name = "build_bazel_rules_nodejs", url = "https://github.com/bazelbuild/rules_nodejs/archive/%s.zip" % RULES_NODEJS_VERSION, strip_prefix = "rules_nodejs-%s" % RULES_NODEJS_VERSION, sha256 = "5ba3c8c209078c2e3f0c6aa4abd01a1a561f92a5bfda04e25604af5f4734d69d", ) load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories") check_bazel_version("0.9.0") node_repositories(package_json = ["//:package.json"]) RULES_TYPESCRIPT_VERSION = "0.10.1" http_archive( name = "build_bazel_rules_typescript", url = "https://github.com/bazelbuild/rules_typescript/archive/%s.zip" % RULES_TYPESCRIPT_VERSION, strip_prefix = "rules_typescript-%s" % RULES_TYPESCRIPT_VERSION, sha256 = "a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485", ) load("@build_bazel_rules_typescript//:defs.bzl", "ts_setup_workspace") ts_setup_workspace() local_repository( name = "rxjs", path = "node_modules/rxjs/src", ) git_repository( name = "com_github_bazelbuild_buildtools", remote = "https://github.com/bazelbuild/buildtools.git", # Note, this commit matches the version of buildifier in angular/ngcontainer # If you change this, also check if it matches the version in the angular/ngcontainer # version in /.circleci/config.yml commit = "b3b620e8bcff18ed3378cd3f35ebeb7016d71f71", ) http_archive( name = "io_bazel_rules_go", url = "https://github.com/bazelbuild/rules_go/releases/download/0.7.1/rules_go-0.7.1.tar.gz", sha256 = "341d5eacef704415386974bc82a1783a8b7ffbff2ab6ba02375e1ca20d9b031c", ) load("@io_bazel_rules_go//go:def.bzl", "go_rules_dependencies", "go_register_toolchains") go_rules_dependencies() go_register_toolchains() # Fetching the Bazel source code allows us to compile the Skylark linter http_archive( name = "io_bazel", url = "https://github.com/bazelbuild/bazel/archive/9755c72b48866ed034bd28aa033e9abd27431b1e.zip", strip_prefix = "bazel-9755c72b48866ed034bd28aa033e9abd27431b1e", sha256 = "5b8443fc3481b5fcd9e7f348e1dd93c1397f78b223623c39eb56494c55f41962", ) # We have a source dependency on the Devkit repository, because it's built with # Bazel. # This allows us to edit sources and have the effect appear immediately without # re-packaging or "npm link"ing. # Even better, things like aspects will visit the entire graph including # ts_library rules in the devkit repository. http_archive( name = "angular_devkit", url = "https://github.com/angular/devkit/archive/v0.3.1.zip", strip_prefix = "devkit-0.3.1", sha256 = "31d4b597fe9336650acf13df053c1c84dcbe9c29c6a833bcac3819cd3fd8cad3", ) http_archive( name = "org_brotli", url = "https://github.com/google/brotli/archive/v1.0.2.zip", strip_prefix = "brotli-1.0.2", sha256 = "b43d5d6bc40f2fa6c785b738d86c6bbe022732fe25196ebbe43b9653a025920d", )
WORKSPACE
1
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017391900473739952, 0.00017065544670913368, 0.0001677515683695674, 0.00017094089707825333, 0.0000020724198748212075 ]
{ "id": 8, "code_window": [ " # Collect the inputs and summary files from our deps\n", " action_inputs = depset(file_inputs,\n", " transitive = [inputs] + [dep.collect_summaries_aspect_result for dep in ctx.attr.deps\n", " if hasattr(dep, \"collect_summaries_aspect_result\")])\n", "\n", " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 220 }
/** * @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 */ /** * @module * @description * Entry point for all public APIs of the common package. */ import {Version} from './util'; /** * @stable */ export const VERSION = new Version('0.0.0-PLACEHOLDER');
packages/compiler/src/version.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001750423398334533, 0.00017238661530427635, 0.0001697308907750994, 0.00017238661530427635, 0.0000026557245291769505 ]
{ "id": 8, "code_window": [ " # Collect the inputs and summary files from our deps\n", " action_inputs = depset(file_inputs,\n", " transitive = [inputs] + [dep.collect_summaries_aspect_result for dep in ctx.attr.deps\n", " if hasattr(dep, \"collect_summaries_aspect_result\")])\n", "\n", " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 220 }
<div ng-style="itemStyle"> <company-name company="offering.company" cell-width="companyNameWidth"> </company-name> <opportunity-name opportunity="offering.opportunity" cell-width="opportunityNameWidth"> </opportunity-name> <offering-name offering="offering" cell-width="offeringNameWidth"> </offering-name> <account-cell account="offering.account" cell-width="accountCellWidth"> </account-cell> <formatted-cell value="offering.basePoints" cell-width="basePointsWidth"> </formatted-cell> <formatted-cell value="offering.kickerPoints" cell-width="kickerPointsWidth"> </formatted-cell> <stage-buttons offering="offering" cell-width="stageButtonsWidth"> </stage-buttons> <formatted-cell value="offering.bundles" cell-width="bundlesWidth"> </formatted-cell> <formatted-cell value="offering.dueDate" cell-width="dueDateWidth"> </formatted-cell> <formatted-cell value="offering.endDate" cell-width="endDateWidth"> </formatted-cell> <formatted-cell value="offering.aatStatus" cell-width="aatStatusWidth"> </formatted-cell> </div>
modules/benchmarks_external/src/naive_infinite_scroll/scroll_item.html
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017573201330378652, 0.00017472676699981093, 0.00017316477897111326, 0.00017480833048466593, 8.889946911949664e-7 ]
{ "id": 8, "code_window": [ " # Collect the inputs and summary files from our deps\n", " action_inputs = depset(file_inputs,\n", " transitive = [inputs] + [dep.collect_summaries_aspect_result for dep in ctx.attr.deps\n", " if hasattr(dep, \"collect_summaries_aspect_result\")])\n", "\n", " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 220 }
/** * @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 {scheduleMicroTask} from '../util'; /** * AnimationPlayer controls an animation sequence that was produced from a programmatic animation. * (see {@link AnimationBuilder AnimationBuilder} for more information on how to create programmatic * animations.) * * @experimental Animation support is experimental. */ export interface AnimationPlayer { onDone(fn: () => void): void; onStart(fn: () => void): void; onDestroy(fn: () => void): void; init(): void; hasStarted(): boolean; play(): void; pause(): void; restart(): void; finish(): void; destroy(): void; reset(): void; setPosition(p: any /** TODO #9100 */): void; getPosition(): number; parentPlayer: AnimationPlayer|null; readonly totalTime: number; beforeDestroy?: () => any; /* @internal */ triggerCallback?: (phaseName: string) => void; /* @internal */ disabled?: boolean; } /** * @experimental Animation support is experimental. */ export class NoopAnimationPlayer implements AnimationPlayer { private _onDoneFns: Function[] = []; private _onStartFns: Function[] = []; private _onDestroyFns: Function[] = []; private _started = false; private _destroyed = false; private _finished = false; public parentPlayer: AnimationPlayer|null = null; public readonly totalTime: number; constructor(duration: number = 0, delay: number = 0) { this.totalTime = duration + delay; } private _onFinish() { if (!this._finished) { this._finished = true; this._onDoneFns.forEach(fn => fn()); this._onDoneFns = []; } } onStart(fn: () => void): void { this._onStartFns.push(fn); } onDone(fn: () => void): void { this._onDoneFns.push(fn); } onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } hasStarted(): boolean { return this._started; } init(): void {} play(): void { if (!this.hasStarted()) { this._onStart(); this.triggerMicrotask(); } this._started = true; } /* @internal */ triggerMicrotask() { scheduleMicroTask(() => this._onFinish()); } private _onStart() { this._onStartFns.forEach(fn => fn()); this._onStartFns = []; } pause(): void {} restart(): void {} finish(): void { this._onFinish(); } destroy(): void { if (!this._destroyed) { this._destroyed = true; if (!this.hasStarted()) { this._onStart(); } this.finish(); this._onDestroyFns.forEach(fn => fn()); this._onDestroyFns = []; } } reset(): void {} setPosition(p: number): void {} getPosition(): number { return 0; } /* @internal */ triggerCallback(phaseName: string): void { const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns; methods.forEach(fn => fn()); methods.length = 0; } }
packages/animations/src/players/animation_player.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017643296450842172, 0.00017372489674016833, 0.00016677977691870183, 0.00017484015552327037, 0.0000026585137220536126 ]
{ "id": 9, "code_window": [ "\n", "\n", "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 223 }
# 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.998379111289978, 0.2934867739677429, 0.0001673539081821218, 0.00558214308694005, 0.4344434440135956 ]
{ "id": 9, "code_window": [ "\n", "\n", "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 223 }
/** * @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 */ // Unique place to configure the browsers which are used in the different CI jobs in Sauce Labs (SL) // and BrowserStack (BS). // If the target is set to null, then the browser is not run anywhere during CI. // If a category becomes empty (e.g. BS and required), then the corresponding job must be commented // out in Travis configuration. var CIconfiguration = { 'Chrome': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Firefox': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'ChromeBeta': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: false}}, 'ChromeDev': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, // FirefoxBeta and FirefoxDev should be target:'BS' or target:'SL', and required:true // Currently deactivated due to https://github.com/angular/angular/issues/7560 'FirefoxBeta': {unitTest: {target: null, required: true}, e2e: {target: null, required: false}}, 'FirefoxDev': {unitTest: {target: null, required: true}, e2e: {target: null, required: true}}, 'IE9': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'IE10': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'IE11': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Edge': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.4': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android5': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android6': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Android7': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Safari7': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari8': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari9': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari10': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'iOS7': {unitTest: {target: 'BS', required: true}, e2e: {target: null, required: true}}, 'iOS8': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'iOS9': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'iOS10': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'WindowsPhone': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}} }; var customLaunchers = { 'DartiumWithWebPlatform': {base: 'Dartium', flags: ['--enable-experimental-web-platform-features']}, 'ChromeNoSandbox': {base: 'Chrome', flags: ['--no-sandbox']}, 'SL_CHROME': {base: 'SauceLabs', browserName: 'chrome', version: '60'}, 'SL_CHROMEBETA': {base: 'SauceLabs', browserName: 'chrome', version: 'beta'}, 'SL_CHROMEDEV': {base: 'SauceLabs', browserName: 'chrome', version: 'dev'}, 'SL_FIREFOX': {base: 'SauceLabs', browserName: 'firefox', version: '54'}, 'SL_FIREFOXBETA': {base: 'SauceLabs', platform: 'Windows 10', browserName: 'firefox', version: 'beta'}, 'SL_FIREFOXDEV': {base: 'SauceLabs', platform: 'Windows 10', browserName: 'firefox', version: 'dev'}, 'SL_SAFARI7': {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.9', version: '7.0'}, 'SL_SAFARI8': {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: '8.0'}, 'SL_SAFARI9': {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: '9.0'}, 'SL_SAFARI10': {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.12', version: '10.0'}, 'SL_IOS7': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '7.1'}, 'SL_IOS8': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '8.4'}, 'SL_IOS9': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '9.3'}, 'SL_IOS10': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '10.0'}, 'SL_IE9': {base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2008', version: '9'}, 'SL_IE10': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2012', version: '10' }, 'SL_IE11': {base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11'}, 'SL_EDGE': { base: 'SauceLabs', browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '14.14393' }, 'SL_ANDROID4.1': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.1'}, 'SL_ANDROID4.2': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.2'}, 'SL_ANDROID4.3': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.3'}, 'SL_ANDROID4.4': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.4'}, 'SL_ANDROID5': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '5.1'}, 'SL_ANDROID6': { base: 'SauceLabs', browserName: 'Chrome', platform: 'Android', version: '6.0', device: 'Android Emulator' }, 'SL_ANDROID7': { base: 'SauceLabs', browserName: 'Chrome', platform: 'Android', version: '7.1', device: 'Android GoogleAPI Emulator' }, 'BS_CHROME': {base: 'BrowserStack', browser: 'chrome', os: 'OS X', os_version: 'Yosemite'}, 'BS_FIREFOX': {base: 'BrowserStack', browser: 'firefox', os: 'Windows', os_version: '10'}, 'BS_SAFARI7': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Mavericks'}, 'BS_SAFARI8': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Yosemite'}, 'BS_SAFARI9': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'El Capitan'}, 'BS_SAFARI10': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Sierra'}, 'BS_IOS7': {base: 'BrowserStack', device: 'iPhone 5S', os: 'ios', os_version: '7.0'}, 'BS_IOS8': {base: 'BrowserStack', device: 'iPhone 6', os: 'ios', os_version: '8.3'}, 'BS_IOS9': {base: 'BrowserStack', device: 'iPhone 6S', os: 'ios', os_version: '9.1'}, 'BS_IOS10': {base: 'BrowserStack', device: 'iPhone SE', os: 'ios', os_version: '10.0'}, 'BS_IE9': {base: 'BrowserStack', browser: 'ie', browser_version: '9.0', os: 'Windows', os_version: '7'}, 'BS_IE10': { base: 'BrowserStack', browser: 'ie', browser_version: '10.1', os: 'Windows', os_version: '8' }, 'BS_IE11': { base: 'BrowserStack', browser: 'ie', browser_version: '11.0', os: 'Windows', os_version: '10' }, 'BS_EDGE': {base: 'BrowserStack', browser: 'edge', os: 'Windows', os_version: '10'}, 'BS_WINDOWSPHONE': {base: 'BrowserStack', device: 'Nokia Lumia 930', os: 'winphone', os_version: '8.1'}, 'BS_ANDROID7': {base: 'BrowserStack', device: 'Google Pixel', os: 'android', os_version: '7.1'}, 'BS_ANDROID6': {base: 'BrowserStack', device: 'Google Nexus 6', os: 'android', os_version: '6.0'}, 'BS_ANDROID5': {base: 'BrowserStack', device: 'Google Nexus 5', os: 'android', os_version: '5.0'}, 'BS_ANDROID4.4': {base: 'BrowserStack', device: 'HTC One M8', os: 'android', os_version: '4.4'}, 'BS_ANDROID4.3': {base: 'BrowserStack', device: 'Samsung Galaxy S4', os: 'android', os_version: '4.3'}, 'BS_ANDROID4.2': {base: 'BrowserStack', device: 'Google Nexus 4', os: 'android', os_version: '4.2'}, 'BS_ANDROID4.1': {base: 'BrowserStack', device: 'Google Nexus 7', os: 'android', os_version: '4.1'} }; var sauceAliases = { 'ALL': Object.keys(customLaunchers).filter(function(item) { return customLaunchers[item].base == 'SauceLabs'; }), 'DESKTOP': [ 'SL_CHROME', 'SL_FIREFOX', 'SL_IE9', 'SL_IE10', 'SL_IE11', 'SL_EDGE', 'SL_SAFARI7', 'SL_SAFARI8', 'SL_SAFARI9', 'SL_SAFARI10' ], 'MOBILE': [ 'SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5', 'SL_ANDROID6', 'SL_ANDROID7', 'SL_IOS7', 'SL_IOS8', 'SL_IOS9', 'SL_IOS10' ], 'ANDROID': [ 'SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5', 'SL_ANDROID6', 'SL_ANDROID7' ], 'IE': ['SL_IE9', 'SL_IE10', 'SL_IE11'], 'IOS': ['SL_IOS7', 'SL_IOS8', 'SL_IOS9', 'SL_IOS10'], 'SAFARI': ['SL_SAFARI7', 'SL_SAFARI8', 'SL_SAFARI9', 'SL_SAFARI10'], 'BETA': ['SL_CHROMEBETA', 'SL_FIREFOXBETA'], 'DEV': ['SL_CHROMEDEV', 'SL_FIREFOXDEV'], 'CI_REQUIRED': buildConfiguration('unitTest', 'SL', true), 'CI_OPTIONAL': buildConfiguration('unitTest', 'SL', false) }; var browserstackAliases = { 'ALL': Object.keys(customLaunchers).filter(function(item) { return customLaunchers[item].base == 'BrowserStack'; }), 'DESKTOP': [ 'BS_CHROME', 'BS_FIREFOX', 'BS_IE9', 'BS_IE10', 'BS_IE11', 'BS_EDGE', 'BS_SAFARI7', 'BS_SAFARI8', 'BS_SAFARI9', 'BS_SAFARI10' ], 'MOBILE': [ 'BS_ANDROID4.3', 'BS_ANDROID4.4', 'BS_ANDROID5', 'BS_ANDROID6', 'BS_ANDROID7', 'BS_IOS7', 'BS_IOS8', 'BS_IOS9', 'BS_IOS10', 'BS_WINDOWSPHONE' ], 'ANDROID': ['BS_ANDROID4.3', 'BS_ANDROID4.4', 'BS_ANDROID5', 'BS_ANDROID6', 'BS_ANDROID7'], 'IE': ['BS_IE9', 'BS_IE10', 'BS_IE11'], 'IOS': ['BS_IOS7', 'BS_IOS8', 'BS_IOS9', 'BS_IOS10'], 'SAFARI': ['BS_SAFARI7', 'BS_SAFARI8', 'BS_SAFARI9', 'BS_SAFARI10'], 'CI_REQUIRED': buildConfiguration('unitTest', 'BS', true), 'CI_OPTIONAL': buildConfiguration('unitTest', 'BS', false) }; module.exports = { customLaunchers: customLaunchers, sauceAliases: sauceAliases, browserstackAliases: browserstackAliases }; function buildConfiguration(type, target, required) { return Object.keys(CIconfiguration) .filter((item) => { var conf = CIconfiguration[item][type]; return conf.required === required && conf.target === target; }) .map((item) => target + '_' + item.toUpperCase()); }
browser-providers.conf.js
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.0001743231259752065, 0.00016955393948592246, 0.00016357180720660836, 0.0001701755536487326, 0.0000029154975891287904 ]
{ "id": 9, "code_window": [ "\n", "\n", "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 223 }
/** * @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 {ChangeDetectorRef, SimpleChange, SimpleChanges, WrappedValue} from '../change_detection/change_detection'; import {Injector, resolveForwardRef} from '../di'; import {ElementRef} from '../linker/element_ref'; import {TemplateRef} from '../linker/template_ref'; import {ViewContainerRef} from '../linker/view_container_ref'; import {Renderer as RendererV1, Renderer2} from '../render/api'; import {stringify} from '../util'; import {createChangeDetectorRef, createInjector, createRendererV1} from './refs'; import {BindingDef, BindingFlags, DepDef, DepFlags, NodeDef, NodeFlags, OutputDef, OutputType, ProviderData, QueryValueType, Services, ViewData, ViewFlags, ViewState, asElementData, asProviderData, shouldCallLifecycleInitHook} from './types'; import {calcBindingFlags, checkBinding, dispatchEvent, isComponentView, splitDepsDsl, splitMatchedQueriesDsl, tokenKey, viewParentEl} from './util'; const RendererV1TokenKey = tokenKey(RendererV1); const Renderer2TokenKey = tokenKey(Renderer2); const ElementRefTokenKey = tokenKey(ElementRef); const ViewContainerRefTokenKey = tokenKey(ViewContainerRef); const TemplateRefTokenKey = tokenKey(TemplateRef); const ChangeDetectorRefTokenKey = tokenKey(ChangeDetectorRef); const InjectorRefTokenKey = tokenKey(Injector); export function directiveDef( checkIndex: number, flags: NodeFlags, matchedQueries: null | [string | number, QueryValueType][], childCount: number, ctor: any, deps: ([DepFlags, any] | any)[], props?: null | {[name: string]: [number, string]}, outputs?: null | {[name: string]: string}): NodeDef { const bindings: BindingDef[] = []; if (props) { for (let prop in props) { const [bindingIndex, nonMinifiedName] = props[prop]; bindings[bindingIndex] = { flags: BindingFlags.TypeProperty, name: prop, nonMinifiedName, ns: null, securityContext: null, suffix: null }; } } const outputDefs: OutputDef[] = []; if (outputs) { for (let propName in outputs) { outputDefs.push( {type: OutputType.DirectiveOutput, propName, target: null, eventName: outputs[propName]}); } } flags |= NodeFlags.TypeDirective; return _def( checkIndex, flags, matchedQueries, childCount, ctor, ctor, deps, bindings, outputDefs); } export function pipeDef(flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef { flags |= NodeFlags.TypePipe; return _def(-1, flags, null, 0, ctor, ctor, deps); } export function providerDef( flags: NodeFlags, matchedQueries: null | [string | number, QueryValueType][], token: any, value: any, deps: ([DepFlags, any] | any)[]): NodeDef { return _def(-1, flags, matchedQueries, 0, token, value, deps); } export function _def( checkIndex: number, flags: NodeFlags, matchedQueriesDsl: [string | number, QueryValueType][] | null, childCount: number, token: any, value: any, deps: ([DepFlags, any] | any)[], bindings?: BindingDef[], outputs?: OutputDef[]): NodeDef { const {matchedQueries, references, matchedQueryIds} = splitMatchedQueriesDsl(matchedQueriesDsl); if (!outputs) { outputs = []; } if (!bindings) { bindings = []; } // Need to resolve forwardRefs as e.g. for `useValue` we // lowered the expression and then stopped evaluating it, // i.e. also didn't unwrap it. value = resolveForwardRef(value); const depDefs = splitDepsDsl(deps, stringify(token)); return { // will bet set by the view definition nodeIndex: -1, parent: null, renderParent: null, bindingIndex: -1, outputIndex: -1, // regular values checkIndex, flags, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries, matchedQueryIds, references, ngContentIndex: -1, childCount, bindings, bindingFlags: calcBindingFlags(bindings), outputs, element: null, provider: {token, value, deps: depDefs}, text: null, query: null, ngContent: null }; } export function createProviderInstance(view: ViewData, def: NodeDef): any { return _createProviderInstance(view, def); } export function createPipeInstance(view: ViewData, def: NodeDef): any { // deps are looked up from component. let compView = view; while (compView.parent && !isComponentView(compView)) { compView = compView.parent; } // pipes can see the private services of the component const allowPrivateServices = true; // pipes are always eager and classes! return createClass( compView.parent !, viewParentEl(compView) !, allowPrivateServices, def.provider !.value, def.provider !.deps); } export function createDirectiveInstance(view: ViewData, def: NodeDef): any { // components can see other private services, other directives can't. const allowPrivateServices = (def.flags & NodeFlags.Component) > 0; // directives are always eager and classes! const instance = createClass( view, def.parent !, allowPrivateServices, def.provider !.value, def.provider !.deps); if (def.outputs.length) { for (let i = 0; i < def.outputs.length; i++) { const output = def.outputs[i]; const subscription = instance[output.propName !].subscribe( eventHandlerClosure(view, def.parent !.nodeIndex, output.eventName)); view.disposables ![def.outputIndex + i] = subscription.unsubscribe.bind(subscription); } } return instance; } function eventHandlerClosure(view: ViewData, index: number, eventName: string) { return (event: any) => dispatchEvent(view, index, eventName, event); } export function checkAndUpdateDirectiveInline( view: ViewData, def: NodeDef, v0: any, v1: any, v2: any, v3: any, v4: any, v5: any, v6: any, v7: any, v8: any, v9: any): boolean { const providerData = asProviderData(view, def.nodeIndex); const directive = providerData.instance; let changed = false; let changes: SimpleChanges = undefined !; const bindLen = def.bindings.length; if (bindLen > 0 && checkBinding(view, def, 0, v0)) { changed = true; changes = updateProp(view, providerData, def, 0, v0, changes); } if (bindLen > 1 && checkBinding(view, def, 1, v1)) { changed = true; changes = updateProp(view, providerData, def, 1, v1, changes); } if (bindLen > 2 && checkBinding(view, def, 2, v2)) { changed = true; changes = updateProp(view, providerData, def, 2, v2, changes); } if (bindLen > 3 && checkBinding(view, def, 3, v3)) { changed = true; changes = updateProp(view, providerData, def, 3, v3, changes); } if (bindLen > 4 && checkBinding(view, def, 4, v4)) { changed = true; changes = updateProp(view, providerData, def, 4, v4, changes); } if (bindLen > 5 && checkBinding(view, def, 5, v5)) { changed = true; changes = updateProp(view, providerData, def, 5, v5, changes); } if (bindLen > 6 && checkBinding(view, def, 6, v6)) { changed = true; changes = updateProp(view, providerData, def, 6, v6, changes); } if (bindLen > 7 && checkBinding(view, def, 7, v7)) { changed = true; changes = updateProp(view, providerData, def, 7, v7, changes); } if (bindLen > 8 && checkBinding(view, def, 8, v8)) { changed = true; changes = updateProp(view, providerData, def, 8, v8, changes); } if (bindLen > 9 && checkBinding(view, def, 9, v9)) { changed = true; changes = updateProp(view, providerData, def, 9, v9, changes); } if (changes) { directive.ngOnChanges(changes); } if ((def.flags & NodeFlags.OnInit) && shouldCallLifecycleInitHook(view, ViewState.InitState_CallingOnInit, def.nodeIndex)) { directive.ngOnInit(); } if (def.flags & NodeFlags.DoCheck) { directive.ngDoCheck(); } return changed; } export function checkAndUpdateDirectiveDynamic( view: ViewData, def: NodeDef, values: any[]): boolean { const providerData = asProviderData(view, def.nodeIndex); const directive = providerData.instance; let changed = false; let changes: SimpleChanges = undefined !; for (let i = 0; i < values.length; i++) { if (checkBinding(view, def, i, values[i])) { changed = true; changes = updateProp(view, providerData, def, i, values[i], changes); } } if (changes) { directive.ngOnChanges(changes); } if ((def.flags & NodeFlags.OnInit) && shouldCallLifecycleInitHook(view, ViewState.InitState_CallingOnInit, def.nodeIndex)) { directive.ngOnInit(); } if (def.flags & NodeFlags.DoCheck) { directive.ngDoCheck(); } return changed; } function _createProviderInstance(view: ViewData, def: NodeDef): any { // private services can see other private services const allowPrivateServices = (def.flags & NodeFlags.PrivateProvider) > 0; const providerDef = def.provider; switch (def.flags & NodeFlags.Types) { case NodeFlags.TypeClassProvider: return createClass( view, def.parent !, allowPrivateServices, providerDef !.value, providerDef !.deps); case NodeFlags.TypeFactoryProvider: return callFactory( view, def.parent !, allowPrivateServices, providerDef !.value, providerDef !.deps); case NodeFlags.TypeUseExistingProvider: return resolveDep(view, def.parent !, allowPrivateServices, providerDef !.deps[0]); case NodeFlags.TypeValueProvider: return providerDef !.value; } } function createClass( view: ViewData, elDef: NodeDef, allowPrivateServices: boolean, ctor: any, deps: DepDef[]): any { const len = deps.length; switch (len) { case 0: return new ctor(); case 1: return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0])); case 2: return new ctor( resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1])); case 3: return new ctor( resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2])); default: const depValues = new Array(len); for (let i = 0; i < len; i++) { depValues[i] = resolveDep(view, elDef, allowPrivateServices, deps[i]); } return new ctor(...depValues); } } function callFactory( view: ViewData, elDef: NodeDef, allowPrivateServices: boolean, factory: any, deps: DepDef[]): any { const len = deps.length; switch (len) { case 0: return factory(); case 1: return factory(resolveDep(view, elDef, allowPrivateServices, deps[0])); case 2: return factory( resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1])); case 3: return factory( resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2])); default: const depValues = Array(len); for (let i = 0; i < len; i++) { depValues[i] = resolveDep(view, elDef, allowPrivateServices, deps[i]); } return factory(...depValues); } } // 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 = {}; export function resolveDep( view: ViewData, elDef: NodeDef, allowPrivateServices: boolean, depDef: DepDef, notFoundValue: any = Injector.THROW_IF_NOT_FOUND): any { if (depDef.flags & DepFlags.Value) { return depDef.token; } const startView = view; if (depDef.flags & DepFlags.Optional) { notFoundValue = null; } const tokenKey = depDef.tokenKey; if (tokenKey === ChangeDetectorRefTokenKey) { // directives on the same element as a component should be able to control the change detector // of that component as well. allowPrivateServices = !!(elDef && elDef.element !.componentView); } if (elDef && (depDef.flags & DepFlags.SkipSelf)) { allowPrivateServices = false; elDef = elDef.parent !; } let searchView: ViewData|null = view; while (searchView) { if (elDef) { switch (tokenKey) { case RendererV1TokenKey: { const compView = findCompView(searchView, elDef, allowPrivateServices); return createRendererV1(compView); } case Renderer2TokenKey: { const compView = findCompView(searchView, elDef, allowPrivateServices); return compView.renderer; } case ElementRefTokenKey: return new ElementRef(asElementData(searchView, elDef.nodeIndex).renderElement); case ViewContainerRefTokenKey: return asElementData(searchView, elDef.nodeIndex).viewContainer; case TemplateRefTokenKey: { if (elDef.element !.template) { return asElementData(searchView, elDef.nodeIndex).template; } break; } case ChangeDetectorRefTokenKey: { let cdView = findCompView(searchView, elDef, allowPrivateServices); return createChangeDetectorRef(cdView); } case InjectorRefTokenKey: return createInjector(searchView, elDef); default: const providerDef = (allowPrivateServices ? elDef.element !.allProviders : elDef.element !.publicProviders) ![tokenKey]; if (providerDef) { let providerData = asProviderData(searchView, providerDef.nodeIndex); if (!providerData) { providerData = {instance: _createProviderInstance(searchView, providerDef)}; searchView.nodes[providerDef.nodeIndex] = providerData as any; } return providerData.instance; } } } allowPrivateServices = isComponentView(searchView); elDef = viewParentEl(searchView) !; searchView = searchView.parent !; if (depDef.flags & DepFlags.Self) { searchView = null; } } const value = startView.root.injector.get(depDef.token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR); if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR || notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) { // Return the value from the root element injector when // - it provides it // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) // - the module injector should not be checked // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) return value; } return startView.root.ngModule.injector.get(depDef.token, notFoundValue); } function findCompView(view: ViewData, elDef: NodeDef, allowPrivateServices: boolean) { let compView: ViewData; if (allowPrivateServices) { compView = asElementData(view, elDef.nodeIndex).componentView; } else { compView = view; while (compView.parent && !isComponentView(compView)) { compView = compView.parent; } } return compView; } function updateProp( view: ViewData, providerData: ProviderData, def: NodeDef, bindingIdx: number, value: any, changes: SimpleChanges): SimpleChanges { if (def.flags & NodeFlags.Component) { const compView = asElementData(view, def.parent !.nodeIndex).componentView; if (compView.def.flags & ViewFlags.OnPush) { compView.state |= ViewState.ChecksEnabled; } } const binding = def.bindings[bindingIdx]; const propName = binding.name !; // Note: This is still safe with Closure Compiler as // the user passed in the property name as an object has to `providerDef`, // so Closure Compiler will have renamed the property correctly already. providerData.instance[propName] = value; if (def.flags & NodeFlags.OnChanges) { changes = changes || {}; const oldValue = WrappedValue.unwrap(view.oldValues[def.bindingIndex + bindingIdx]); const binding = def.bindings[bindingIdx]; changes[binding.nonMinifiedName !] = new SimpleChange(oldValue, value, (view.state & ViewState.FirstCheck) !== 0); } view.oldValues[def.bindingIndex + bindingIdx] = value; return changes; } // This function calls the ngAfterContentCheck, ngAfterContentInit, // ngAfterViewCheck, and ngAfterViewInit lifecycle hooks (depending on the node // flags in lifecycle). Unlike ngDoCheck, ngOnChanges and ngOnInit, which are // called during a pre-order traversal of the view tree (that is calling the // parent hooks before the child hooks) these events are sent in using a // post-order traversal of the tree (children before parents). This changes the // meaning of initIndex in the view state. For ngOnInit, initIndex tracks the // expected nodeIndex which a ngOnInit should be called. When sending // ngAfterContentInit and ngAfterViewInit it is the expected count of // ngAfterContentInit or ngAfterViewInit methods that have been called. This // ensure that dispite being called recursively or after picking up after an // exception, the ngAfterContentInit or ngAfterViewInit will be called on the // correct nodes. Consider for example, the following (where E is an element // and D is a directive) // Tree: pre-order index post-order index // E1 0 6 // E2 1 1 // D3 2 0 // E4 3 5 // E5 4 4 // E6 5 2 // E7 6 3 // As can be seen, the post-order index has an unclear relationship to the // pre-order index (postOrderIndex === preOrderIndex - parentCount + // childCount). Since number of calls to ngAfterContentInit and ngAfterViewInit // are stable (will be the same for the same view regardless of exceptions or // recursion) we just need to count them which will roughly correspond to the // post-order index (it skips elements and directives that do not have // lifecycle hooks). // // For example, if an exception is raised in the E6.onAfterViewInit() the // initIndex is left at 3 (by shouldCallLifecycleInitHook() which set it to // initIndex + 1). When checkAndUpdateView() is called again D3, E2 and E6 will // not have their ngAfterViewInit() called but, starting with E7, the rest of // the view will begin getting ngAfterViewInit() called until a check and // pass is complete. // // This algorthim also handles recursion. Consider if E4's ngAfterViewInit() // indirectly calls E1's ChangeDetectorRef.detectChanges(). The expected // initIndex is set to 6, the recusive checkAndUpdateView() starts walk again. // D3, E2, E6, E7, E5 and E4 are skipped, ngAfterViewInit() is called on E1. // When the recursion returns the initIndex will be 7 so E1 is skipped as it // has already been called in the recursively called checkAnUpdateView(). export function callLifecycleHooksChildrenFirst(view: ViewData, lifecycles: NodeFlags) { if (!(view.def.nodeFlags & lifecycles)) { return; } const nodes = view.def.nodes; let initIndex = 0; for (let i = 0; i < nodes.length; i++) { const nodeDef = nodes[i]; let parent = nodeDef.parent; if (!parent && nodeDef.flags & lifecycles) { // matching root node (e.g. a pipe) callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++); } if ((nodeDef.childFlags & lifecycles) === 0) { // no child matches one of the lifecycles i += nodeDef.childCount; } while (parent && (parent.flags & NodeFlags.TypeElement) && i === parent.nodeIndex + parent.childCount) { // last child of an element if (parent.directChildFlags & lifecycles) { initIndex = callElementProvidersLifecycles(view, parent, lifecycles, initIndex); } parent = parent.parent; } } } function callElementProvidersLifecycles( view: ViewData, elDef: NodeDef, lifecycles: NodeFlags, initIndex: number): number { for (let i = elDef.nodeIndex + 1; i <= elDef.nodeIndex + elDef.childCount; i++) { const nodeDef = view.def.nodes[i]; if (nodeDef.flags & lifecycles) { callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++); } // only visit direct children i += nodeDef.childCount; } return initIndex; } function callProviderLifecycles( view: ViewData, index: number, lifecycles: NodeFlags, initIndex: number) { const providerData = asProviderData(view, index); if (!providerData) { return; } const provider = providerData.instance; if (!provider) { return; } Services.setCurrentNode(view, index); if (lifecycles & NodeFlags.AfterContentInit && shouldCallLifecycleInitHook(view, ViewState.InitState_CallingAfterContentInit, initIndex)) { provider.ngAfterContentInit(); } if (lifecycles & NodeFlags.AfterContentChecked) { provider.ngAfterContentChecked(); } if (lifecycles & NodeFlags.AfterViewInit && shouldCallLifecycleInitHook(view, ViewState.InitState_CallingAfterViewInit, initIndex)) { provider.ngAfterViewInit(); } if (lifecycles & NodeFlags.AfterViewChecked) { provider.ngAfterViewChecked(); } if (lifecycles & NodeFlags.OnDestroy) { provider.ngOnDestroy(); } }
packages/core/src/view/provider.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.025269025936722755, 0.0007424996583722532, 0.00016546269762329757, 0.00017345297965221107, 0.0033587736543267965 ]
{ "id": 9, "code_window": [ "\n", "\n", "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 223 }
/** * @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 {EmitterVisitorContext} from '@angular/compiler/src/output/abstract_emitter'; import * as o from '@angular/compiler/src/output/output_ast'; import {JitEmitterVisitor} from '@angular/compiler/src/output/output_jit'; import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_reflector'; const anotherModuleUrl = 'somePackage/someOtherPath'; { describe('Output JIT', () => { describe('regression', () => { it('should generate unique argument names', () => { const externalIds = new Array(10).fill(1).map( (_, index) => new o.ExternalReference(anotherModuleUrl, `id_${index}_`, {name: `id_${index}_`})); const externalIds1 = new Array(10).fill(1).map( (_, index) => new o.ExternalReference( anotherModuleUrl, `id_${index}_1`, {name: `id_${index}_1`})); const ctx = EmitterVisitorContext.createRoot(); const converter = new JitEmitterVisitor(new JitReflector()); converter.visitAllStatements( [o.literalArr([...externalIds1, ...externalIds].map(id => o.importExpr(id))).toStmt()], ctx); const args = converter.getArgs(); expect(Object.keys(args).length).toBe(20); }); }); }); }
packages/compiler/test/output/output_jit_spec.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017637039127293974, 0.00017284051864407957, 0.00017038712394423783, 0.0001723023015074432, 0.0000022371016257238807 ]
{ "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 }
workspace(name = "bazel_integration_test") http_archive( name = "build_bazel_rules_nodejs", url = "https://github.com/bazelbuild/rules_nodejs/archive/0.4.1.zip", strip_prefix = "rules_nodejs-0.4.1", sha256 = "e9bc013417272b17f302dc169ad597f05561bb277451f010043f4da493417607", ) load("@build_bazel_rules_nodejs//:defs.bzl", "node_repositories") node_repositories(package_json = ["//:package.json"]) http_archive( name = "build_bazel_rules_typescript", url = "https://github.com/bazelbuild/rules_typescript/archive/0.10.1.zip", strip_prefix = "rules_typescript-0.10.1", sha256 = "a2c81776a4a492ff9f878f9705639f5647bef345f7f3e1da09c9eeb8dec80485", ) load("@build_bazel_rules_typescript//:defs.bzl", "ts_setup_workspace") ts_setup_workspace() local_repository( name = "angular", path = "node_modules/@angular/bazel", ) local_repository( name = "rxjs", path = "node_modules/rxjs/src", ) git_repository( name = "io_bazel_rules_sass", remote = "https://github.com/bazelbuild/rules_sass.git", tag = "0.0.3", ) load("@io_bazel_rules_sass//sass:sass.bzl", "sass_repositories") sass_repositories()
integration/bazel/WORKSPACE
1
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00018528243526816368, 0.00017330983246210963, 0.00016648347082082182, 0.00017194166139233857, 0.000006704422503389651 ]
{ "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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js export default [ [ [ 'મ.રાત્રિ', 'સવારે', 'બપોરે', 'સાંજે', 'રાત્રે' ], [ 'મધ્યરાત્રિ', 'સવારે', 'બપોરે', 'સાંજે', 'રાત્રે' ], ], [ [ 'મધ્યરાત્રિ', 'સવારે', 'બપોરે', 'સાંજે', 'રાત્રે' ], , [ 'મધ્યરાત્રિ', 'સવાર', 'બપોર', 'સાંજ', 'રાત્રિ' ] ], ['00:00', ['04:00', '12:00'], ['12:00', '16:00'], ['16:00', '20:00'], ['20:00', '04:00']] ];
packages/common/locales/extra/gu.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017486467550043017, 0.00017011718591675162, 0.00016680412227287889, 0.00016939998022280633, 0.0000030501155379170086 ]